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

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

我正在使用 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. 设置您的模型,以便评论 belongs_to 一个用户,以及一个用户 has_many 评论
  2. 创建评论时将 user_id 保存为 current_user.id
  3. 在您的 partial/view 中显示评论时执行如下操作:

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

原文:

您不需要在控制器中执行此操作。

在您的视图中简单地尝试一下:

<%= image_tag(current_user.avatar) %>