如何为rails中的多个属性实现通用验证方法

时间:2017-05-25 04:24:26

标签: ruby-on-rails validation rails-activerecord

我有一个具有两个时间属性的模型,如下所示,

class Notification < ActiveRecord::Base
  validate :time1_must_be_in_the_past?
  validate :time2_must_be_in_the_past?

  def time1_must_be_in_the_past?
    if time1.present? && time1 > DateTime.now
      errors.add(:time1, "must be in the past")
    end
  end
  def time2_must_be_in_the_past?
    if time2.present? && time2 > DateTime.now
      errors.add(:time2, "must be in the past")
    end
  end
end

我想有一种验证方法可以应对这两种验证。该怎么做呢。

2 个答案:

答案 0 :(得分:1)

根据你的描述,我认为你可能正在寻找这样的东西:

class Notification < ActiveRecord::Base
  validate :time_must_be_in_the_past

  def time_must_be_in_the_past
    if time1.present? && time1 > DateTime.now
      errors.add(:time1, "must be in the past")
    end

    if time2.present? && time2 > DateTime.now
      errors.add(:time2, "must be in the past")
    end
  end
end

答案 1 :(得分:1)

您可以使用followinf代码段

class Notification < ActiveRecord::Base
  validate :time_must_be_in_the_past?

  def time_must_be_in_the_past?
    [time1, time2].each do |time|  
      errors.add(:time, "must be in the past") if time.present? && time> DateTime.now
    end
  end
end