ユーザーが誕生日を日付として編集する場所としてテキストフィールドを使用しようとしています。例では、私は取り組んでいますが、誕生日はまだ存在しません。追加しようとしている誕生日は です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