views:

33

answers:

2
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.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.

A: 

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.

Topher Fangio
+2  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"...

Daniel Kristensen