Rails 3:如何防止我的验证通过“零时间"来自 time_select 下拉列表? [英] Rails 3: How to prevent my validations to pass a "nil time" from time_select dropdowns?

查看:34
本文介绍了Rails 3:如何防止我的验证通过“零时间"来自 time_select 下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有提示(选择时间"...)的 time_select 并希望确保用户实际输入了有效时间.但是,如果表单在没有被选中的情况下提交(因此选择了空提示选项),我的验证不会出现任何错误.

I use time_select with a prompt ("Choose hours"...) and would like to make sure, the user actually enters a valid time. But if the form is submitted without a time being selected (so with the empty prompt options selected) I don't get any errors from my validations.

我的验证:

validates :start_time, :presence => true, :allow_nil => false, :allow_blank => false

原因是当它们为空时,rails 会自动将 time_select 字段的输入转换为此日期:

The reason is that rails turns the input from the time_select fields automatically into this date, when they are empty:

0001-01-01 00:00:00

有什么好的方法可以防止这种情况发生吗?

Is there a nice way to prevent this from happening?

谢谢!

推荐答案

如果你想强制执行一个验证,至少从这个 SO Post 和这个 SO Post,您需要进行自定义验证.

If you want to enforce a validation it looks like, at least from this SO Post and this SO Post, you would want to do a custom validation.

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

显然这是一个愚蠢的例子,但我希望它能让你明白.

Obviously this is a silly example but I hope it gets the idea across.

这篇关于Rails 3:如何防止我的验证通过“零时间"来自 time_select 下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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