Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将用户id添加到注释模型_Ruby On Rails_Comments_Associations - Fatal编程技术网

Ruby on rails 将用户id添加到注释模型

Ruby on rails 将用户id添加到注释模型,ruby-on-rails,comments,associations,Ruby On Rails,Comments,Associations,我将遵循本教程: 当使用commenter和comment时,它可以工作,用户可以添加名称和消息,但我希望将注释与用户id关联(我已经有用户) 它使用 rails生成模型注释注释器:string body:text post:references,但我想用用户id关联(user\u id:integer?)替换Comment:string)。在前面的一个问题中,有人建议使用author\u id:integer,但它不起作用。不确定从何处开始,而且似乎没有关于该主题的任何教程(我已经阅读了关于

我将遵循本教程:

当使用
commenter
comment
时,它可以工作,用户可以添加名称和消息,但我希望将注释与用户id关联(我已经有用户)

它使用
rails生成模型注释注释器:string body:text post:references
,但我想用用户id关联(
user\u id:integer
?)替换
Comment:string
)。在前面的一个问题中,有人建议使用
author\u id:integer
,但它不起作用。不确定从何处开始,而且似乎没有关于该主题的任何教程(我已经阅读了关于关联等的RoR帮助指南,但找不到使用注释模型生成用户id的正确方法)

注释\u controller.rb

def create
@listing = Listing.find(params[:listing_id])
@comment = @listing.comments.create(params[:comment])
redirect_to listing_path(@listing)
end

您可以生成如下注释模式:

rails生成模型注释用户:引用正文:文本发布:引用

您指定的
引用
类型实际上将创建一个
用户id:integer
列,并将
所属
关联添加到
注释
模型:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

如何在评论和评论表单所在的/posts/1页面上获取特定评论的用户id?(因此每个注释旁边都有用户id)当我在dev数据库中查找时,注释的用户id为空。创建新注释(我将发布我的注释控制器)时,如何将用户ID与如下内容关联:
@post.comments.first.user\u ID
。或者您只需返回
用户
实例:
@post.comments.first.User
。若要将用户分配给新注释,您需要获取当前用户实例,然后使用它创建注释:
@comment=@listing.comments.create(参数[:comment].merge(用户:用户))
。我假设您使用的是Rails 3.2或更低版本。顺便说一句,我使用的是Rails 4.0.2,您需要使用强参数,否则注释创建将无法正常工作。请看这里:
class Comment < ActiveRecord::Base
  belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'
  belongs_to :post
end