在 Rails 中发表评论时显示用户名 [英] Show username when posting comments in Rails

查看:44
本文介绍了在 Rails 中发表评论时显示用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户发布专辑评论时,我有一个名为 Pins 的应用.我创建了一个评论模型供其他用户评论评论.我正在努力让评论说发布者",然后显示发布它们的用户的姓名.部分代码如下:

I have an app when users post album reviews called Pins. I created a comments model for other users to comment on the reviews. I'm struggling getting the comments to say "Posted by" and then show the user's name who posts them. Here is some of the code:

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

The pins model has_many :comments The user model has_many :comments The comments model 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 上发布的一些其他答案,但没有骰子.我想说的是:

I've tried some of the other answers posted on Stack Overflow, but no dice. I'm trying to say something like:

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

推荐答案

您正在为 Comment 的用户名字段分配一个 User 实例.我假设用户名属性是数据库中的一个字符串.所以如果你想让名字出现在评论中,那么你需要为它分配当前用户的名字.

You are assigning a User instance to the username field for the Comment. I assume that the username attribute is a string in the database. So if you want the name to appear in the comment then you need to assign it the name from the current user.

所以:

@comment.username = current_user.name

如果您已经在 CommentUser 之间建立了关联,那么您可以这样做:

If you already have an association between Comment and User then you could do:

@comment.user = current_user

<%= @comment.user.name %>

这篇关于在 Rails 中发表评论时显示用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆