简体   繁体   中英

Ruby on Rails 3 “.each do”

I am listing comments for blog posts. For example, I have 4 comments for one blog post. If I print "@comments.count" in my view, it returns 4, correctly. But if I do "@comments.each do |comment|", it returns me those 4 comments and one blank comment at the end. So it returns me always one more blank comment.

controller

def show
  @post = BlogPost.find params[:id]
  @blog_comment = @post.blog_comments.new
  @comments = @post.blog_comments
  @categories = BlogCategory.where(locale: I18n.locale)
end

view

<ul>
  <% @comments.each do |comment| %>
    <li><%= comment.body %></li>    
  <% end %>
</ul>

I feel dumb to ask those questions, but I can't find solution.

In your show action, change the order of lines 2 and 3.

You're creating a new (empty) blog comment in line 2 and then creating an array of the blog comments (including the empty one) on line 3.

Robin

Robin is right that you create an empty comment that is part of the list. "comments.count" still reports 4 because it triggers a SQL count query that doesn't contain the new (unsaved) comment. The easiest way to solve this is probably to instantiate the new comment for the form not as part of the association:

@blog_comment = BlogComment.new( blog_post_id: @post.id)

Another way would be to filter out the new comment by using the "new_record?" method on the comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM