Multifield/range validation

。_饼干妹妹 提交于 2019-12-25 03:47:13

问题


how would I validate that one field of my Model is "smaller" compared to another?

class Event < ActiveRecord::Base
  validates :start, :presence => true
  validates :stop, :presence => true
end

In addition - how could I make sure that the "difference" between the two values doesn't exceed a maximum range?

Cheers


回答1:


I have a validation that's similar to this to make sure school years begin before they end and are not longer than a year.

  validate :beginning_before_ending, :not_longer_than_year


  def beginning_before_ending
    errors.add(:base, 'Beginning date must be before ending date') if self.beginning > self.ending
  end

  def not_longer_than_year
    errors.add(:base, 'School year is too long') if self.beginning + 1.year < self.ending
  end

So you could do something like this.

  validate :start_before_stop, :not_longer_than_whatever

  def start_before_stop
    errors.add(:base, 'Start must be before stop') if self.start > self.stop
  end

  def not_longer_than_whatever
    errors.add(:base, 'Range is too long') if self.start + whatever < self.stop
  end



回答2:


I strongly recommend the validates_timeliness gem for these sorts of date validations. It makes it much simpler and more reliable to check for these sorts of things, and in a way that's also more readable so someone else can quickly grok the intent of the validation.




回答3:


So, just picking an example range of 30 days:

class Event < ActiveRecord::Base
  @@range = 30

  validates :start, :presence => true
  validates :stop, :presence => true

  validate :start_stop_values
  def start_stop_values
    unless ( stop - start ) >= @@range.days
      errors.add( :base, "Start needs to be #{@@range} days before stop.")
    end
  end
end


来源:https://stackoverflow.com/questions/6239895/multifield-range-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!