Rails 日期因型号而更改
我有一个带有日期选择的表格。
我有以下形式:
<%= date_select :user, :birthday, {:start_year => Time.now.year, :end_year => 1910,:order => [:day,:month,:year], :prompt => { :day => 'day', :month => 'month', :year => 'year' }}, { :class => "default" } %>
模型中的验证:
validates :birthday, :if => :should_validate_birthday?,
:presence => {:message => "Please enter your friend's birthdate"},
:date => { :after => Date.civil(1910,1,1), :before => Date.today, :message => "Please enter a valid date"}
这是用户在日志中提交内容的示例:
"user"=>{"name"=>"rewrwe", "birthday(3i)"=>"1", "birthday(2i)"=>"", "birthday(1i)"=>"2008", "email"=>""}}
请注意,月份的值为空。
在控制器中,我创建用户,
create
@user = User.new(params[:user])
If @user.save
#go to the confirm page
end
end
即使缺少月份,也不会显示错误消息,因为由于某种原因,当我尝试保存模型时,它将空月份转换为“一月”或 01。
这非常令人沮丧,因为我不这样做希望用户意外提交错误数据。
我怎样才能阻止 Rails 这样做并确保提交所有日期信息?
I have a form with a date select.
I have the following form:
<%= date_select :user, :birthday, {:start_year => Time.now.year, :end_year => 1910,:order => [:day,:month,:year], :prompt => { :day => 'day', :month => 'month', :year => 'year' }}, { :class => "default" } %>
Validation in my model:
validates :birthday, :if => :should_validate_birthday?,
:presence => {:message => "Please enter your friend's birthdate"},
:date => { :after => Date.civil(1910,1,1), :before => Date.today, :message => "Please enter a valid date"}
Here is an example of what the user submits in the log:
"user"=>{"name"=>"rewrwe", "birthday(3i)"=>"1", "birthday(2i)"=>"", "birthday(1i)"=>"2008", "email"=>""}}
NOTE that the value for the month is blank.
IN the controller I create the user
create
@user = User.new(params[:user])
If @user.save
#go to the confirm page
end
end
No error messages are shown even though the month is missing because for some reason when I try to save the model it converts an empty month to "January" or 01.
This is very frustrating as I don't want users to submit bad data by accident.
How can I stop Rails from doing this and make sure all the date information is submitted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用
attr_accessor
分隔三个字段:然后在您的视图中,每个字段都有不同的选择。这就是 date_select 所做的全部工作,但它在视图中而不是在模型中将它们分开,这使得验证每个字段变得困难。
Separate the three fields with
attr_accessor
:And then in your view just have different selects for each of them. That's all the date_select does but it splits them up in the view, rather than in the model, which makes it hard to validate each field.