How to handle validation with has_many relationship
class Article < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :article
validates_presence_of :body
validates_presence_of :author_name
end
If I leave the author_name as blank then I am getting proper validation error. All good.
>> Article.first.comments.create(:body => 'dummy body').errors.full_messages
=> ["Please enter your name"]
Look at this example.
>> a = Article开发者_如何学Go.first
>> a.comments.create(:body => 'dummy body')
>> a.errors.full_messages
["Comments is invalid"]
I send instance of article (a in this case) to view layer. I was wondering how do I get access to the pricise error 'please enter your name' from instance object a.
You could assign the newly created comment to it's own variable and send that to the view as well.
@article = Article.first
@comment = @article.comments.create(:body => 'dummy body')
You can then use error_messages_for 'article', 'comment'
to display errors for both objects. I don't know if there is a way to automatically display the individual child errors instead of the "X is invalid"...
Just complementing Daniel's answer, in case you want to customize the 'Comments is invalid'
error message, I found a way to do it through i18n:
# config/locales/en.yml
en:
activerecord:
attributes:
article:
comments: Comment
This way you will get 'Comment is invalid'
which is syntactically correct :)
You can also change the 'is invalid'
part:
# config/locales/en.yml
en:
activerecord:
errors:
models:
article:
attributes:
comments:
invalid: are invalid
And this way you will get 'Comments are invalid'
.
Assuming the view is the form that attempted to create the object, you should be able to do exactly what you did above:
@article.errors.full_messages
Other views that just have access to the object (such as the index or show views) will not have any errors because that array is only filled when attempting to create or update the article.
精彩评论