我有一个名为 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
end
这是现在的应用程序:http://powerful-reaches-7038.herokuapp.com http://powerful-reaches-7038.herokuapp.com
我已经尝试过 Stack Overflow 上发布的其他一些答案,但没有任何结果。我想说的是:
<strong>Posted <%= time_ago_in_words(comment.created_at) %> ago by <%= comment.user.name %></strong>
您正在分配一个User
实例的用户名字段Comment
。我假设用户名属性是数据库中的字符串。因此,如果您希望该名称出现在评论中,则需要为其分配当前用户的名称。
So:
@comment.username = current_user.name
如果您之间已经有关联Comment
and User
那么你可以这样做:
@comment.user = current_user
<%= @comment.user.name %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)