Home Error when delete comment Ruby on Rails
Reply: 1

Error when delete comment Ruby on Rails

Kamran Sadixov
1#
Kamran Sadixov Published in 2017-12-29 20:42:58Z

When I delete comment I see

undefined method 'each' for nil:NilClass

Also, the user cannot delete his account if has posted... It makes the error.

This is code

<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 %>
Rockwell Rice
2#
Rockwell Rice Reply to 2017-12-29 20:47:16Z

Your are not checking if any comments are present before looping through them. So if there are no comments you are calling each on nil.

This should fix it

<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>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315864 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO