在Rails中发布评论时显示用户名
当用户发布名为Pins的专辑评论时,我有一个应用程序。 我为其他用户创建了一个评论模型,以评论评论。 我正在努力让评论说“发布者”,然后显示发布者的姓名。 以下是一些代码:
pin模型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上发布的其他一些答案,但没有骰子。 我想说的是:
Posted ago by
您正在为Comment
的用户名字段分配User
实例。 我假设username属性是数据库中的字符串。 因此,如果您希望该名称出现在注释中,则需要为其指定当前用户的名称。
所以:
@comment.username = current_user.name
如果您已经在Comment
和User
之间建立了关联,那么您可以:
@comment.user = current_user <%= @comment.user.name %>
您保存用户名
@comment.username = current_user
并显示:
<%= comment.user.name %>
但它必须是
<%= comment.username %>