我正在尝试使用文本字段作为用户将生日编辑为日期的地方。有了这个例子,我正在研究,还没有生日。我要添加的生日是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
这是模型方法。您可以看到我在 :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
这是我的模型验证方法中 p 语句的打印输出
"BIRTHDAY = "
"03/21/1986"
1986-03-21 12:00:00 -0600
我也刚刚注意到,如果我做一个日期10/10/1980
,它工作得很好,如果我做一个日期21/03/1986
,我得到一个invalid date
错误。
编辑 这里有一些可能有帮助的信息:
看法:
<%= form_for(@userProfile, :url => {:controller => "contacts", :action => "update_user"}, :html => {:class => "form grid_6 edit_profile_form"}, :method => :put ) do |f| %>
...
<%= f.fields_for :user_details do |d| %>
<%= d.label :birthday, raw("Birthday <small>mm/dd/yyyy</small>") %>
<%= d.text_field :birthday %>
...
<% end %>
用户模型
class User < ActiveRecord::Base
...
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company, :user_details_attributes
validates_presence_of :email
has_one :user_details, :dependent => :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