错误..尝试将用户头像包含在已发布的评论中

时间:2015-03-05 03:36:28

标签: ruby-on-rails carrierwave avatars

我使用CarrierWave进行头像上传。上传和删除头像在用户编辑视图中工作并显示在其他视图中。但是当试图将阿凡达包含在评论中时,我遇到了错误。

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

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

我不确定自己做错了什么。

  **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

1 个答案:

答案 0 :(得分:1)

编辑:

我建议不要针对每条评论保存用户的头像。

相反,我会这样做:

  1. 设置模型,以便评论belongs_to用户和用户has_many评论
  2. 创建评论时,将user_id保存为current_user.id
  3. 在显示评论的部分/视图中执行以下操作:
  4. <%= image_tag(@comment.user.avatar) %>

    原件:

    您不应该在控制器中执行此操作。

    在您的视图中尝试使用此功能:

    <%= image_tag(current_user.avatar) %>