Rails do not display validation error messages on a linked model

I have a simple but nasty problem with displaying validation errors for post comments. The error partially shows errors for messages, but despite the fact that validation works with comments, errors are not displayed.

part of the comment is added to the post message:

<%= form_for([@post, @post.comments.build]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

partial errors

<% if object.errors.any? %>
<h2>Errors:</h2>
<ul>
  <% object.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>  
</ul>

models:

 class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy

  validates :title, :content, :presence => true
  validates :title, length: { minimum: 3 }
  validates :title, :uniqueness => true

end

class Comment < ActiveRecord::Base
  belongs_to :post

  validates :body,      presence: true
  validates :commenter, presence: true, length: { minimum: 3 }

end

I have been looking for an answer for some time, but cannot make it work.

+4
source share
1 answer

Add this line to the model. Post

validates_associated :comments

0
source

All Articles