User has many comments, comment belongs to many users. How do I fix this error?
undefined method `first_name' for nil:NilClass
when I try to do
<h3>Comments</h3>
<% @guide.comments.each do |comment| %>
<div>
<p><%= comment.user.first_name %></p>
</div>
<% end %>
user.rb
has_many :comments
comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
end
comments migration (I added a user_id column):
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.integer :user_id
t.timestamps
add_foreign_key :comments, :guides
end
end
end
comments controller:
def create
@comment = Comment.new(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end