Undefined method 'username' in comments even though users are referenced

Viewed 142

I have tried setting up a comment system on my application. I have made a migration for the comments so all the comments have a user_id and post_id referenced with them. I have added has_many :comments, through: :posts in my user model. I have also added has_many :comments in my posts controller. In my comments controller I have also added belongs_to :post and the same for belongs_to :user. The problem occurs though when I try to call anything from the user model through an html.erb. When I make a comment through the console everything goes through fine and I can see what user made the comment, but when I try to even display any comments everything go sideways. Here is the part which is causing the error:

<% @comments.each do |comment| %>
  <h3><%= comment.user.username %></h3>
  <h4><%= comment.body %></h4>
  </div>
<% end %>

It throws me an error in the username part giving me: undefined method `username' for nil:NilClass. Also, this occurs one every post even if that post doesn't have any comments. The body does work though.

2 Answers
undefined method `username' for nil:NilClass

This is caused by the fact that username is not a property of nil You need to account for the fact that for some of your records, probably legacy data before you wrote the code to handle the associations, there is no user associated with a comment.

Change your view code to check for nil

<% @comments.each do |comment| %>
  <h3><%= comment.user.username unless comment.user.blank? || comment.user.username.blank?%></h3>
  <h4><%= comment.body %></h4>
  </div> <%# why a random closing div here, remove it or move it to a more appropriate location to match an opening div%>
<% end %>

Or perhaps a little nicer

<% @comments.each do |comment| %>
  <h3>
     <%if comment.user.blank?%>
        No user associated with this comment
     <%= else comment.user.username.blank?%>
  </h3>
  <h4><%= comment.body %></h4>
  </div> <%# why a random closing div here, remove it or move it to a more appropriate location to match an opening div%>
<% end %>

Root, because when you created comment, you did not set comment.user (example comment.user = current_user) before save.
Check your code in CommentsController -> method create

Related