删除注释Ruby on Rails时出错

时间:2017-12-29 20:42:58

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

当我删除评论时,我看到了

  

未定义的方法'each'代表nil:NilClass

此外,如果已发布,则用户无法删除其帐户...会出错。

这是代码

<p id="notice"><%= notice %></p>

<h1>Comments</h1>

<table>
  <thead>
    <tr>
      <th>Link</th>
      <th>Body</th>
      <th>User</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @comments.each do |comment| %>
      <tr>
        <td><%= comment.link_id %></td>
        <td><%= comment.body %></td>
        <td><%= comment.user %></td>
        <td><%= link_to 'Show', comment %></td>
        <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
        <td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Comment', new_comment_path %>

1 个答案:

答案 0 :(得分:0)

在循环播放之前,您不会检查是否有任何评论。因此,如果没有评论,您在nil上调用each

这应该解决它

<tbody>
   <% if @comments.any? %> <----- Add in this line and the end below
    <% @comments.each do |comment| %>
      <tr>
        <td><%= comment.link_id %></td>
        <td><%= comment.body %></td>
        <td><%= comment.user %></td>
        <td><%= link_to 'Show', comment %></td>
        <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
        <td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  <% end %> <---- here
</tbody>