Rails的date_select助手和验证 [英] Rails date_select helper and validation

查看:134
本文介绍了Rails的date_select助手和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Rails应用程序的模型支持格式的日期字段:

I have a date field in a model backed form in my Rails App:

<%= f.date_select :birthday,
  {:start_year => Time.now.year,
  :end_year => 1900,
  :use_short_month => true,
  :order => [:month, :day, :year],
  :prompt => {:month => 'Month', :day => 'Day', :year => 'Year'}},
  {:class => 'year',
  :id => 'user_birthday'}
%>

它被模型中的code。使用验证:

It is being validated in the model code using:

validates_presence_of :birthday, :message => 'is a required field'

不幸的是,如果用户输入的局部值,如刚刚年,形式仍然提交没有发生错误。而是一个时髦的日期值被写入到数据库。如何使所有三个字段是强制性的?

Unfortunately, if the user enters a partial value such as just the year, the form still submits without an error. Instead a funky date value gets written to the db. How do I make all three fields be mandatory?

我想编写一个自定义验证这一点,但我不知道如何正确地访问indvidual件生日元素。我怎样才能做到这一点?

I'd like to write a custom validation for this, but I don't know how to properly access the indvidual pieces of the birthday element. How can I do this?

谢谢! 萌

推荐答案

我认为你必须创建在控制器中进行验证。

I think you would have to create the validation in the controller itself.

日期部分被传递到生日(1I)生日(2I)生日(3I)。这里的问题是,它们被立即传递属性和任何校验发生从而之前时分配

The date parts are being passed to birthday(1i), birthday(2i) and birthday(3i). The problem here is that they are assigned immediately when passing the attributes and thus before any validations occur.

您也可以覆盖属性= 方法来创建自己的验证,但我不会建议你这样做。

You could also overwrite the attributes= method to create your own validation there, but I would not suggest you to do that.

请记住,如果你这样做验证,它可能是很好的验证对任何不正确的日期为好。 (二月,在传递将产生三月的第二个,而不是一个错误的实例月31日)。

Keep in mind that if you do validations, it might be good to validate against any incorrect date as well. (for instance 31st of February, which when passed will yield 2nd of March and not an error).

我觉得这里的主要问题是,ActiveRecord的实际替换为 1 的空值,创造了日期之前 ,这也意味着,如果游客只是经过一年,日期将在1月的这一年的第一个创建的。我想这是一个预期的行为,从而允许使用的只有一个年/月/日选择,仍然创造一个有用的日期。

I think the main issue here is that ActiveRecord is actually replacing the empty values with 1 before creating the Date, which also means that if the visitor pass only the year, the date will be created on the 1st of January that year. I guess that is an expected behaviour to allow use of only one of year/month/day select and still create a useful date.

这篇关于Rails的date_select助手和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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