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>
<开发者_JAVA百科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.user
isn't nil before trying to call a method on it. An if
statement can do this for you:
<% @blog.comments.each do |comment| %>
<h3><%= comment.user.email if comment.user %></h3>
</div>
<% end %>
It looks like you haven't associated a user with the comment in this case. First you have to set the user in some way, for example when you create it. If you don't always want to do this, you need to check if the user is actually set or not.
There is a possibility that you haven't set email
for the user.
For the app to not throw an error message anymore, you can try this:
<%= comment.user.try(:email) %>
However I think it's good practice a model validation should be here.
The problem is values of deleted db entity/entities.
For preventing all of the errors you have to use
<%= comment.user.try(:email) %>
just like from above.
enjoy your coding ^^
精彩评论