Rails 3: Why `errors` Hash is empty for nested model (all errors are in the parent model)
I'm using Devise and have models set up like this:
User
has_one :profile
Profile
belongs_to :user
has_one :address
Address
belongs_to :pro开发者_JAVA技巧file
For testing, I caused errors on the form (it's a nested form, using all 3 models). This is the resulting errors hash (@user.errors hash
):
{
:email=>["can't be blank"],
:password_confirmation=>[],
:password=>["can't be blank"],
:"profile.first_name"=>["can't be blank","is too short (minimum is 1 characters)"]
:"profile.address.street"=>["can't be blank"],
}
All the errors are expected, but the hash's key format is unexpected (:"profile.address.street"
) - I would have thought each nested model's errors
hash would contain the errors for that model ?
I checked inside the @user.profile.errors
hash, and that is empty!
How do I get the nested-model specific errors into the relevant errors
hash in the nested model?
UPDATE
I hacked out a solution here. Had a question on that too, so the solution isn't posted as an answer to this question :)
Ran into this not too long ago and had to cook up some code to pluck these out myself. It isn't supported by default in Rails - Ryan Daigle touches on it here a bit.
Try this:
@user.profile.valid?
@user.profile.errors
精彩评论