【问题标题】:Error when delete comment Ruby on Rails删除评论 Ruby on Rails 时出错
【发布时间】:2017-12-29 20:42:58
【问题描述】:

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

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

另外,用户不能删除他的帐户,如果已经发布...它会出错。

这是代码

<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 %>

【问题讨论】:

  • 你能分享你CommentsController的代码吗?更具体地说,销毁操作。
  • 请分享您的控制器代码。它将帮助我们更多地回答。

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


【解决方案1】:

在循环遍历它们之前,您没有检查是否存在任何 cmets。因此,如果没有 cmets,您将在 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>

【讨论】:

  • 我知道我在做假设,但根据您编写控制器的方式,@comments 至少应该是一个空集合,对吧?这样您就不需要检查(除非您想显示某种空消息)。
  • 很难说,我猜它是@comments = Comment.all 或与帖子有关,在这种情况下,我认为这可能是产生错误的罪魁祸首,但这是我的一个假设。
猜你喜欢
  • 1970-01-01
  • 2012-11-07
  • 2019-02-20
  • 2016-04-17
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
相关资源
最近更新 更多