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.