Hi,
I’m working on my User model, which derives from Party, and parties have
many e-mail addresses, telephones, and mailing addresses. When I save
the user model, the validations occur, but the child error messages
appear to be summarized. I expected the child errors to be listed in
detail, as in “Put in the address, dummy”. Instead, rails returns
“Emails is invalid”, or “Addresses is Invalid” for the message.
In irb, I see that there are some interesting methods for the user
object:
validate_associated_records_for_emails
validate_associated_records_for_addresses
validate_associated_records_for_phones
They appear to add the child messages to the @errors object of the user
model, but they don’t seem to be called by @user.save!
Also, I tried adding the following to the view, it didn’t appear to
help:
<%= error_messages_for :address %>
<%= error_messages_for :email %>
<%= error_messages_for :phone %>
What is the rails way to force the display of the child errors? Or
perhaps more appropriately, what is the correct way to handle validation
when working with parent and child records on the same form.
Thank you!
app/models/party.rb
class Party < ActiveRecord::Base
has_many :addresses
has_many :emails
has_many :phones
end
app/models/user.rb
Class User < Party
end
app/models/email.rb
class Email < ActiveRecord::Base
belongs_to :party
validates_presence_of :address, “Put in the address, dummy”
end
app/controllers/account_controller.rb
def signup
@user = User.new
@user.emails << Email.new
@user.phones << Phone.new
@user.addresses << Address.new
end
def signup_post
@user = User.new(params[:user])
params[:email].each {|e| @user.emails << Email.new(e)}
params[:address].each {|a| @user.addresses << Address.new(a)}
params[:phone].each {|t| @user.phones << Phone.new(t)}
@user.save!
flash[:notice] = “Thanks for signing up!”
rescue ActiveRecord::RecordInvalid
render :action => ‘signup’
end
Regards,
Rich