Rails 4。每个打印一个额外的空结果

时间:2016-02-07 13:24:54

标签: ruby-on-rails ruby

我有一个链接的评论表,表格如下:

<%= form_for([@link, @link.item_comments.build]) do |f| %>
  <%= f.hidden_field :user_id, value: current_user.id %>
  <%= f.text_area :content %>
  <%= f.submit "Submit" %>
<% end %>

我正在将评论打印到页面上:

<ul>
    <% @link.item_comments.each do |comment| %>
      <li><%= comment.content %> <%= comment.user_name %></li>
      Points: <%= comment.points %>
    <% end %>
  </ul>

但是当我查看页面时,我会在最后打印出一个额外的空元素。谁能解释一下发生了什么?我认为这可能与表单中的.build有关,但我找不到任何相关内容。

干杯

1 个答案:

答案 0 :(得分:0)

你是正确的@link.item_comments是原因。

来自docs

  

collection.build(attributes = {},...)返回一个或多个集合类型的新对象,这些对象已使用属性实例化并通过外键链接到此对象,但尚未但是得救了。

但即使它尚未保存,但它会被添加,以便它显示在您each循环中使用的form_for([@link, ItemComment.new])集合中。

从代码的其余部分看,无论如何,当评论被保存时,您必须将评论与链接相关联,并且您可以form_for使用'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => '213h2i3121h12osiajls', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], // Here after user I need to add another config user-two 'user-two' => [ 'identityClass' => 'app\models\SecondUser', 'enableAutoLogin' => true, ],