1

I have started the "Get Started Guide" from the ruby on rails website. Everything works fine, but when I change the order of showing all comments and than display the comments-form in the other way round, than the form_forfunction adds a empty comments model to @post.comments and so, I display one empty comment in the loop. Here is the view:

<h1><%= @post.name %></h1>
<p><%= @post.text %></p>
<h2>Add comment</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <p>
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
<h2>Comments</h2>
<%= render @post.comments %>

The loop display two comments. One, that exists in the db and one, that has just empty attributes. If I delete the form, than all is shown up correct.

1
  • You should also display your posts controller. Commented Jul 12, 2015 at 17:31

2 Answers 2

1

You can select only your persisted comments:

<%= render @post.comments.select(&:persisted?) %>

Sign up to request clarification or add additional context in comments.

Comments

1

When you do post.comments.build against some post, it will be added to the post.comments collection and will be displayed along with other comments.

You can always use persisted to check if the object is present in database meaning id is assigned to it.

 @post.comments.select(&:persisted?)

Note: .present? check donot work here so you have to use .persisted.? present check only assosiated to the parent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.