开发者

Multifield/range validation

开发者 https://www.devze.com 2023-03-10 16:57 出处:网络
how would I validate that one field of my Model is \"smaller\" compared to another? class Event < ActiveRecord::Base

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


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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号