Rails试图将字符串转换为日期时间,但它没有保存到db

我正在尝试使用文本字段作为用户将日期作为日期进行编辑的地方。 通过这个例子,我正在努力,还没有生日。 我想要添加的生日是03/21/1986

这是控制器方法:

 # PUT /contacts/1/edit # actually updates the users data def update_user @userProfile = User.find(params[:id]) @userDetails = @userProfile.user_details respond_to do |format| if @userProfile.update_attributes(params[:user]) format.html { flash[:success] = "Information updated successfully" redirect_to(edit_profile_path) } else format.html { flash[:error] = resource.errors.full_messages render :edit } end end end 

这是模型方法。 您可以看到我正在调用validation方法:birthday将其转换为日期。 一切似乎都有效,但没有任何东西保存到数据库,我没有错误。

 # validate the birthday format def birthday_is_date p 'BIRTHDAY = ' p birthday_before_type_cast new_birthday = DateTime.strptime(birthday_before_type_cast, "%m/%d/%Y").to_date p new_birthday unless(Chronic.parse(new_birthday).nil?) errors.add(:birthday, "is invalid") end birthday = new_birthday end 

这是我的模型validation方法中的p语句的打印输出

 "BIRTHDAY = " "03/21/1986" 1986-03-21 12:00:00 -0600 

我也注意到,如果我的日期是10/10/1980 ,它的工作正常,如果我的日期是21/03/1986 ,我会收到invalid date错误。

编辑这里有一些可能有用的信息:

视图:

  {:controller => "contacts", :action => "update_user"}, :html => {:class => "form grid_6 edit_profile_form"}, :method => :put ) do |f| %> ...  <%= d.label :birthday, raw("Birthday mm/dd/yyyy") %>  ...  

用户模型

 class User  :destroy accepts_nested_attributes_for :user_details end 

user_details模型

 require 'chronic' class UserDetails < ActiveRecord::Base belongs_to :user validate :birthday_is_date attr_accessible :first_name, :last_name, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company # validate the birthday format def birthday_is_date p 'BIRTHDAY = ' p birthday_before_type_cast new_birthday = DateTime.strptime(birthday_before_type_cast, "%m/%d/%Y").to_date p new_birthday unless(Chronic.parse(new_birthday).nil?) errors.add(:birthday, "is invalid") end birthday = new_birthday end end 

 def birthday_is_date begin birthday = DateTime.strptime(birthday_before_type_cast, "%m/%d/%Y").to_date rescue errors.add(:birthday, "is invalid") end end 

我最终使用了虚拟属性,现在似乎正在运行。

我把它添加到我的模型中

 attr_accessible :birthday_string def birthday_string @birthday_string || birthday.strftime("%d-%m-%Y") end def birthday_string=(value) @birthday_string = value self.birthday = parse_birthday end private def birthday_is_date errors.add(:birthday_string, "is invalid") unless parse_birthday end def parse_birthday Chronic.parse(birthday_string) end