Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.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 使用关联获取所有相关记录_Ruby On Rails_Ruby_Postgresql - Fatal编程技术网

Ruby on rails 使用关联获取所有相关记录

Ruby on rails 使用关联获取所有相关记录,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,我无法理解如何使用关联而不是关联id(如user\u id和comment\u id)获取所有相关记录。 假设我有三个模型,分别是用户、帖子、评论、图像和关联 User has_many :posts has_many :comments Post belongs_to :user has_many :comments has_many :images Comment belongs_to :user belongs_to :post Image belon

我无法理解如何使用关联而不是关联id(如
user\u id
comment\u id
)获取所有相关记录。 假设我有三个模型,分别是用户、帖子、评论、图像和关联

User
  has_many :posts
  has_many :comments

Post
  belongs_to :user
  has_many :comments
  has_many :images

Comment
  belongs_to :user
  belongs_to :post

Image
  belongs_to :post
现在我有一个
user\u id
的user,并将user查找为:

@user = User.find_by_id(params[:id])
@comments = @user.comments
现在我想把这些评论和他们每个人的帖子的相关记录一起拿来。我想要post散列,而不是对应于每个注释的
post\u id
。 我想在一个查询中实现这一点。 如果你有什么想法,请建议我

使用
包括(:关联)

注意:这将进行另一次(第二次)查询

或者,将其包括在初始查询中:

@user = User.where(id: params[:id]).includes(comments: :post)
使用
包括(:关联)

注意:这将进行另一次(第二次)查询

或者,将其包括在初始查询中:

@user = User.where(id: params[:id]).includes(comments: :post)

尝试
@user.comments.first.post
,它将返回一个
post
实例。注意此方法中需要解决的问题,但这超出了您的问题范围。感谢您的考虑@mudasobwa。但我的问题是,我希望comments集合已经有了与每个评论对应的post记录,而不是post_id。我不想循环获取每个评论的post
@user.comments。首先。post
,它将返回一个
post
实例。注意此方法中需要解决的问题,但这超出了您的问题范围。感谢您的考虑@mudasobwa。但我的问题是,我希望评论集合中的每个评论都有相应的帖子记录,而不是帖子id。我不想循环获取每个帖子的帖子抱歉@Uzbekjon,这将导致在评论中找不到名为“posts”的关联错误。这是一个打字错误。只需将其更改为
post
,因为它是属于
协会的。这不会替换comments集合中的post_id。这将再次返回post\u id而不是完整的post hash它不会替换
post\u id
,但它还将包含一个名为
post
的属性。请查看抱歉@Uzbekjon,这将导致在评论中找不到名为“posts”的关联错误。这是一个打字错误。只需将其更改为
post
,因为它是属于
协会的。这不会替换comments集合中的post_id。这将再次返回post\u id而不是完整的post hash它不会替换
post\u id
,但它还将包含一个名为
post
的属性。退房