0

When i execute the command to appear the column of user when have the many comments this error:

      <% post.comments.each do |comment|   %>
        <div id="comments" >
          <%= comment.user.email if comment.user.email != nil %>
               <%= comment.comment %>
        </div>
NoMethodError in Posts#index

Showing /Users/overallduka/Blog1/app/views/posts/index.html.erb where line #50 raised:

undefined method `email' for nil:NilClass
Extracted source (around line #50):

The comments model have belongs_to user and the user model have has_many comments, as right this, but i dont identifie the problem, i check and all my comments have user_id , please some solution please.

4

1 に答える 1

1

The problem is that at least one of the comments on your post object has a nil value for the user association. You're checking that email is not nil, but you're not checking whether user itself is nil (which is what is triggering the NoMethodError).

As a start, I would change this line:

<%= comment.user.email if comment.user.email != nil %>

to:

<%= comment.user && comment.user.email %>

This is a handy pattern in ruby which first checks that comment.user is defined, and if it is defined returns the second argument, i.e. comment.user.email. If comment.user is not defined (or nil, or false) then the second argument is not evaluated, and the return value is nil (so if no user is defined, then comment.user.email is never evaluated so you don't get an error).

于 2013-01-13T01:50:53.487 に答える