我将time_select与提示符(“选择小时数”...)一起使用,并希望确保用户实际输入有效时间。但是如果在没有选择时间的情况下提交表单(因此选择了空提示选项),我的验证不会出现任何错误。
我的验证:
validates :start_time, :presence => true, :allow_nil => false, :allow_blank => false
原因是rails将time_select字段的输入自动转换为此日期,当它们为空时:
0001-01-01 00:00:00
有没有一种很好的方法可以防止这种情况发生?
谢谢!
答案 0 :(得分:1)
如果您想强制执行验证,至少从此SO Post和此SO Post开始,您可能希望进行自定义验证。
class Whatever < ActiveRecord::Base
validate :time_scope
...
private
def time_scope
if Whatever.where(<pick the record entered>).time == "0001-01-01 00:00:00"
errors.add(:time, "Oh no you didn't enter that garbage time on my watch!")
end
end
end
显然这是一个愚蠢的例子,但我希望它可以解决这个问题。