如何根据特定范围验证模型的日期属性(在运行时评估) [英] How to validate a model's date attribute against a specific range (evaluated at run time)

查看:72
本文介绍了如何根据特定范围验证模型的日期属性(在运行时评估)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有日期属性的模型,每个模型我想根据给定的范围验证这些日期。一个基本的例子是:

I have several models with a date attribute and for each model I'd like to validate these dates against a given range. A basic example would be:

validates_inclusion_of  :dated_on, :in => Date.new(2000,1,1)..Date(2020,1,1)

理想情况我想在运行时评估日期范围,使用类似于 named_scope 使用的方法,例如:

Ideally I'd like to evaluate the date range at runtime, using a similar approach as named_scope uses, e.g:

validates_inclusion_of  :dated_on, :in => lambda {{ (Date.today - 2.years)..(Date.today + 2.years)}}


$ b $当然,上述方法不行,那么实现相同结果的最好办法是什么呢?

The above doesn't work of course, so what is the best way of achieving the same result?

推荐答案

如果每个类的验证相同,答案相当简单:将验证方法放在模块中并混合在每个模型中,然后使用验证来添加验证:

If the validation is the same for each class, the answer is fairly simple: put a validation method in a module and mix it in to each model, then use validate to add the validation:

# in lib/validates_dated_on_around_now
module ValidatesDatedOnAroundNow
  protected

  def validate_dated_around_now
    # make sure dated_on isn't more than five years in the past or future
    self.errors.add(:dated_on, "is not valid") unless ((5.years.ago)..(5.years.from_now)).include?(self.dated_on)
  end
end

class FirstModel
  include ValidatesDatedOnAroundNow
  validate :validate_dated_around_now
end

class SecondModel
  include ValidatesDatedOnAroundNow
  validate :validate_dated_around_now
end

如果你想要每个模型的不同范围,你可能想要更像这样的东西:

If you want different ranges for each model, you probably want something more like this:

module ValidatesDateOnWithin
  def validates_dated_on_within(&range_lambda)
    validates_each :dated_on do |record, attr, value|
      range = range_lambda.call
      record.errors.add(attr_name, :inclusion, :value => value) unless range.include?(value)
    end
  end
end

class FirstModel
  extend ValidatesDatedOnWithin
  validates_dated_on_within { ((5.years.ago)..(5.years.from_now)) }
end

class SecondModel
  extend ValidatesDatedOnWithin
  validates_dated_on_within { ((2.years.ago)..(2.years.from_now)) }
end

这篇关于如何根据特定范围验证模型的日期属性(在运行时评估)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆