简体   繁体   English

Ruby on Rails 3“ .each do”

[英]Ruby on Rails 3 “.each do”

I am listing comments for blog posts. 我正在列出博客文章的评论。 For example, I have 4 comments for one blog post. 例如,我对一篇博客文章有4条评论。 If I print "@comments.count" in my view, it returns 4, correctly. 如果我在视图中打印“ @ comments.count”,它将正确返回4。 But if I do "@comments.each do |comment|", it returns me those 4 comments and one blank comment at the end. 但是,如果我执行“ @ comments.each做| comment |”,它将在最后返回我那4条评论和一条空白评论。 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. 在您的表演动作中,更改第2行和第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. 您要在第2行中创建一个新的(空白)博客评论,然后在第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. “ comments.count”仍然报告4,因为它触发了一个不包含新(未保存)注释的SQL计数查询。 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?" 另一种方法是使用“ new_record?”过滤掉新评论。 method on the comment. 评论方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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