Ruby on rails 如何在评论中添加用户名?
当用户创建注释时。我们怎么能加上他的名字呢?我尝试了current_用户,但很明显,这只是当前用户的名字,而不是发表评论的人的名字 在用户模型中Ruby on rails 如何在评论中添加用户名?,ruby-on-rails,ruby,Ruby On Rails,Ruby,当用户创建注释时。我们怎么能加上他的名字呢?我尝试了current_用户,但很明显,这只是当前用户的名字,而不是发表评论的人的名字 在用户模型中有许多:注释,如::commentable在注释模型中属于:commentable,多态性:true,在路由中被分解为资源:用户做资源:注释结束 views/comments/_comments.html.erb <div id="comments"> <% @comments.each do |comment| %> &
有许多:注释,如::commentable
在注释模型中属于:commentable,多态性:true
,在路由中被分解为资源:用户做资源:注释结束
views/comments/_comments.html.erb
<div id="comments">
<% @comments.each do |comment| %>
<div class="comment">
<%= current_user.name %>
<%= simple_format comment.content %>
</div>
<% end %>
评论控制器
class CommentsController
假设您
用户模型:
注释模型
注释迁移
编辑:如果要处理多态关联,请按如下方式编辑模型:
class User
has_many :comments, as: :commentable
...
end
class Comment
belongs_to :commentable, polymorphic: true
...
end
编辑:插入注释迁移
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.references :commentable, polymorphic: true, index: true
t.timestamps null: false
end
end
end
class CreateComments
编辑与估价控制器相关的内容
@valuation.commentable.user.name
获取用户-这假设您的估价设置了与评论模型的正确关联@commentable=@valuation
和@comments=@commentable.comments
。它们没有错,但是在这种情况下,用相同的值保存变量是没有任何意义的@comment.commentable.user.name
周围的代码是正确的。这告诉我,你的控制器一定出了问题
最终解决方案
将
添加到_comments.html.erb在用户发表评论之前,您如何验证其使用。您需要收集他的详细信息或通过第三方API进行身份验证,并获取我已有的信息def set_comment@comment=comment.find(params[:id])end
。如果我在视图中使用@comment.user.name
,我会得到一个错误:未定义的方法user for#
。谢谢你!您的用户和评论迁移情况如何?请尝试使用owner
而不是user
。对不起,我不是指代码,而是指VALUATIONS的值。嗯,在控制台上你会得到你想要的结果。您希望在何处检索创建用户名?在表演中?请更新与整个相关控制器的职位。让我们。
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.belongs_to :user, index: true
t.timestamps null: false
end
end
end
@comment = Comment.find(params[:id])
@comment.user.name
class User
has_many :comments, as: :commentable
...
end
class Comment
belongs_to :commentable, polymorphic: true
...
end
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.references :commentable, polymorphic: true, index: true
t.timestamps null: false
end
end
end