How to handle validation with a 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 author_name blank, I get the correct validation error. Things are good.

>> Article.first.comments.create(:body => 'dummy body').errors.full_messages
=> ["Please enter your name"]

      

Take a look at this example.

>> a = Article.first
>> a.comments.create(:body => 'dummy body')
>> a.errors.full_messages
["Comments is invalid"]

      

I am submitting a copy of the article (in this case) to view the layer. I was wondering how I can access the pricise error "please enter your name" from an object instance a.

+2


source to share


3 answers


You can assign the newly created comment to your own variable and send it to the view as well.

@article = Article.first  
@comment = @article.comments.create(:body => 'dummy body')

      



Then you can use error_messages_for 'article', 'comment'

to display errors for both objects. I don't know if there is a way to automatically display individual child errors instead of "X is invalid" ...

+4


source


Just complementing Daniel's answer, if you want to customize the error message 'Comments is invalid'

, I found a way to do it via i18n:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      article:
        comments: Comment

      

This way you get 'Comment is invalid'

which is syntactically correct :) You can also change the part 'is invalid'

:



# config/locales/en.yml
en:
  activerecord:
    errors:
      models:
        article:
          attributes:
            comments:
              invalid: are invalid

      

And so you get 'Comments are invalid'

.

+1


source


Assuming the view is the form that was trying to create the object, you should be able to do exactly what you did above:

@article.errors.full_messages

      

Other views that only have access to the object (such as the index view or views) will not have any errors because this array is only populated when trying to create or update an article.

0


source







All Articles