我正在构建一个Rails 4应用程序,它有一个约会模型。我正在试图找出如何编写自定义验证器以防止用户在上午6:30之前和晚上9:00之后安排约会。 DateTime是我的模型的appointment_date字段的数据类型。
我最初的想法是在我的模型中编写一个方法来定义验证,但我不知道如何构造这样的方法,或者这是解决问题的最佳方法。
我在互联网上搜索了如何实现目标的线索,但没有找到任何有用的信息。我非常感谢有关如何做到这一点的任何建议。
答案 0 :(得分:0)
您可以像活动记录一样创建自己的。这样可以实现干净,便携,易于测试的自定义验证。示例可能如下所示:
使用以下命令创建 app / validators / during_business_hours_validator.rb :
class DuringBusinessHoursValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# example - do whatever you want here
unless value.present? && during_business_hours(value)
record.errors[attribute] << 'must be during business hours'
end
end
def during_business_hours(time)
# from http://stackoverflow.com/q/10090962/525478
Range.new(
Time.local(time.year, time.month, time.day, 6, 30),
Time.local(time.year, time.month, time.day, 21)) === time
end
end
然后,在你的模型中添加:
validates :appointment_date,
during_business_hours: true