Jonathan Maddison
Jonathan Maddison

Reputation: 1107

NoMethodError "undefined method `email' for nil:NilClass"

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?

Upvotes: 2

Views: 8577

Answers (4)

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 ^^

Upvotes: 0

Tu H.
Tu H.

Reputation: 496

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.

Upvotes: 0

Jakob W
Jakob W

Reputation: 3377

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.

Upvotes: 3

Teddy
Teddy

Reputation: 18572

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 %>

Upvotes: 8

Related Questions