开发者

Rails date being changed by model

开发者 https://www.devze.com 2023-04-12 02:33 出处:网络
I have a form with a date select. I have the following form: <%= date_select :user, :bi开发者_Python百科rthday, {:start_year => Time.now.year, :end_year => 1910,:order => [:day,:month,:y

I have a form with a date select.

I have the following form:

<%= date_select :user, :bi开发者_Python百科rthday, {: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?


Separate the three fields with attr_accessor:

class User < ActiveRecord::Base
  attr_accessor :birthday_year, :birthday_month, :birthday_date
  validates_presence_of :birthday_year, :birthday_month, :birthday_date
  # ...
end

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消