多场/范围验证

时间:2011-06-04 22:59:32

标签: ruby-on-rails ruby-on-rails-3

我如何验证模型中的一个字段与另一个字段相比“更小”?

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

此外 - 我怎样才能确保两个值之间的“差异”不超过最大范围?

干杯

3 个答案:

答案 0 :(得分:1)

我有一个与此类似的验证,以确保学年在结束前开始,且不超过一年。

  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

所以你可以这样做。

  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

答案 1 :(得分:1)

我强烈建议validates_timeliness gem进行这些日期验证。它使检查这些事情变得更加简单和可靠,并且以更可读的方式使得其他人可以快速了解验证的意图。

答案 2 :(得分:0)

所以,只需选择30天的示例范围:

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