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.
The problem is that at least one of the
commentson yourpostobject has anilvalue for theuserassociation. You’re checking thatemailis not nil, but you’re not checking whetheruseritself is nil (which is what is triggering theNoMethodError).As a start, I would change this line:
to:
This is a handy pattern in ruby which first checks that
comment.useris defined, and if it is defined returns the second argument, i.e.comment.user.email. Ifcomment.useris not defined (ornil, orfalse) then the second argument is not evaluated, and the return value is nil (so if no user is defined, thencomment.user.emailis never evaluated so you don’t get an error).