I am having an issue with the below code in one of my views:
<% @blog.comments.each do |comment| %>
<h3><%= comment.user.email %></h3>
</div>
<% end %>
Which is producing an error:
NoMethodError in Blogs#show
...
undefined method `email' for nil:NilClass
The below code however works without error:
<% @blog.comments.each do |comment| %>
<%= comment.body %>
<% end %>
Comment is declared as:
class Comment < ActiveRecord::Base
belongs_to :blog
belongs_to :user
end
And the email attribute is accessible in another view as:
<% @users.each do |user| %>
<tr>
<td><%= link_to user.username, user %></td>
<td><%= user.email %></td>
</tr>
<% end %>
To me it looks like comment.user isn’t being recognised as an instance of User model. What am I doing wrong?
You need to check that
comment.userisn’t nil before trying to call a method on it. Anifstatement can do this for you: