문제

I'm trying to render comments under a blog post. Simple authentication makes sure only I can see the destroy links.

The issue is this: an additional destroy link gets rendered even when there are zero comments, that redirects to posts/:post_id/comments, which doesn't exist. Only the :create and :destroy resources exist.

The destroy links of the individual comments get rendered correctly and behave correctly, i.e. send delete request to posts/:post_id/:id.

My code:

<!-- views/posts/show.html.erb -->

<% provide(:title, @post.title) %>

<%= render "show_listing", :post => @post %>

<% if admin? %>
  <p><%= link_to "Edit", edit_post_path(@post) %></p>
  <p><%= link_to "Destroy", post_path(@post), :confirm => "Zeker weten?", :method => :delete %></p>
<% end %>

<p><%= link_to "Terug naar blog", blog_path %></p>

<h2>Laat een reactie achter:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <p>
    <%= f.label :author, "Naam" %><br>
    <%= f.text_field :author %>
  </p>
  <p>
    <%= f.label :body, "Bericht" %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit "Verzend" %>
  </p>
<% end %>

<h2>Reacties</h2>
<% @post.comments.each do |comment| %>
  <p><%= comment.author %></p>
  <p><%= comment.body %></p>
  <% if admin? %>
    <p>
      <%= link_to 'Destroy Comment', post_comment_path(@post, comment),
               method: :delete,
               confirm: 'Are you sure?' %>
    </p>
  <% end %>
<% end %>

This is the html being produced. The code inside the .each block gets executed, even when there are zero comments.

<p></p>
<p></p>
  <p>
    <a data-confirm="Are you sure?" data-method="delete" href="/posts/16/comments/" rel="nofollow">Destroy Comment</a>
  </p>

Update: this is very weird. When I try in rails console:

post = Post.find(16)
post.comments.empty? # => true

But when enclosing my block in an unless statement:

<% unless @post.comments.empty? %>
  ...
<% end %>

The code still gets executed!! Change to if @post.comments.empty? and it doesn't show anything. (no destroy link).

Update: after rake db:reset and server reset, no changes. Putting

<%= debug comment %>

inside the block returns this:

--- !ruby/object:Comment
attributes:
  id: 
  author: 
  body: 
  post_id: 1
  created_at: 
  updated_at: 

So there is one phantom comment associated with each post. How did this get here?

도움이 되었습니까?

해결책

The problem is with your form declaring @post.comments.build. That's making a new (but not yet saved) comment on @post, so that when it comes to your loop, the test @post.comments.empty? does pass because you just made a new comment for the collection.

Also maybe just a style thing, but I find the behavior of .blank? much more appealing than .empty?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top