Search code examples
ruby-on-railsruby-on-rails-3.2commentsmodel-associations

Error displaying a user's name and user's avatar who is associated with a comment


With the code below...

<%= image_tag comment.user.avatar.url(:medium), class: "circle-extrasmall" %>
<%= comment.user.name %>

I get the error...

undefined method `avatar' for nil:NilClass

I think I've created the right associations for users and comments.

Here's what is in the controller...

class CommentsController < ApplicationController

def create
@challenge = Challenge.find(params[:challenge_id])
@comment = @challenge.comments.create(params[:comment])
@comment.user_id = current_user
flash[:notice] = "Comment has been created!"
redirect_to @challenge
end

end

and here's what is in the model...

class Comment < ActiveRecord::Base
attr_accessible :challenge_id, :user_id, :text

validates :user_id, presence: true

belongs_to :challenge
belongs_to :user
end

But, I'm not sure what is causing that error. I'm new to Ruby-on-Rails. Thanks in advance for your suggestions.


Solution

  • Pleas change the create action code

    @comment = @challenge.comments.new(params[:comment])
    @comment.user_id = current_user.id
    @comment.save
    

    As you already have some records which don't have user_id. So you need to remove those record or for now you can do like the followings to get rid of this error

    <% comment_user = comment.user%>
    <%= image_tag comment_user.avatar.url(:medium), class: "circle-extrasmall" unless comment_user.blank?%>
    <%= comment_user.name unless comment_user.blank?%>