ruby-on-railscarrierwaveavatars

Error.. trying to include the User Avatar with a posted comment


I'm using CarrierWave for my Avatar Uploading. The uploading and deletion of the avatar works in the user edit view and displays in otherviews. But when trying to include an Avatar with a comment I run into an error.

TypeError in CommentsController#create
can't cast AvatarUploader to string

app/controllers/comments_controller.rb:10:in `create'

I'm not sure what I've done wrong.

  **comments_controller.rb**

  def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comments_params)
  @comment.user_name = current_user.user_name
  @comment.avatar = current_user.avatar
  if @comment.save
   redirect_to @post
  else
   flash.now[:danger] = "error"
  end
  end

Solution

  • Edit:

    I would suggest not saving the user's avatar against each comment.

    Rather, I would do this:

    1. Set up your models so that a comment belongs_to a user, and a user has_many comments
    2. When creating a comment save the user_id as current_user.id
    3. In your partial/view when displaying the comments do something like:

    <%= image_tag(@comment.user.avatar) %>

    Original:

    You shouldn't need to do this in your controller.

    Try simply this in your view:

    <%= image_tag(current_user.avatar) %>