0

当用户发布专辑评论时,我有一个名为 Pins 的应用程序。我为其他用户创建了一个评论模型来评论评论。我正在努力让评论说“发布者”,然后显示发布它们的用户的名字。这是一些代码:

引脚模型has_many :comments 用户模型has_many :comments 评论模型belongs_to :pin belongs_to :user

这是评论控制器:

def create
@pin = Pin.find(params[:pin_id])
@comment = @pin.comments.create(params[:comment])
@comment.username = current_user

respond_to do |format|
  if @comment.save
    format.html { redirect_to @pin, notice: 'Comment was successfully created.' }
    format.json { render json: @comment, status: :created, location: @comment }
  else
    format.html { render action: "new" }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end

结尾

这是现在的应用程序:http: //powerful-reaches-7038.herokuapp.com

我已经尝试了 Stack Overflow 上发布的其他一些答案,但没有骰子。我想说的是:

<strong>Posted <%= time_ago_in_words(comment.created_at) %> ago by <%= comment.user.name %></strong>
4

2 回答 2

2

您正在将User实例分配给Comment. 我假设用户名属性是数据库中的字符串。因此,如果您希望名称出现在评论中,那么您需要为其分配当前用户的名称。

所以:

@comment.username = current_user.name

如果您已经在 和 之间建立了关联CommentUser那么您可以执行以下操作:

@comment.user = current_user

<%= @comment.user.name %>
于 2013-08-26T03:32:16.200 回答
0

您将用户名保存在

@comment.username = current_user

并显示:

<%= comment.user.name %>

但它必须是

<%= comment.username %>
于 2013-08-25T23:42:58.303 回答