Multifield/range validation

2019-09-02 06:15发布

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

3条回答
在下西门庆
2楼-- · 2019-09-02 06:51

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
查看更多
再贱就再见
3楼-- · 2019-09-02 07:00

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
查看更多
别忘想泡老子
4楼-- · 2019-09-02 07:10

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.

查看更多
登录 后发表回答