Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.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_Search_Activerecord_Associations - Fatal编程技术网

Ruby on rails 如何搜索关联记录具有给定属性值的关联?

Ruby on rails 如何搜索关联记录具有给定属性值的关联?,ruby-on-rails,ruby,search,activerecord,associations,Ruby On Rails,Ruby,Search,Activerecord,Associations,我正在使用RubyonRails4,我想搜索关联记录,其中关联记录具有给定的属性值。也就是说,我有一个有很多:通过像下面这样的关联 class Article < ActiveRecord::Base has_many :comment_associations has_many :comments, through: :comment_associations end 类文章

我正在使用RubyonRails4,我想搜索关联记录,其中关联记录具有给定的属性值。也就是说,我有一个
有很多:通过像下面这样的关联

class Article < ActiveRecord::Base
  has_many :comment_associations
  has_many :comments, through: :comment_associations
end
类文章
注释
具有
标题
属性


如何搜索
注释\u关联
其中
注释
具有给定的
标题

这就是您想要的吗

# Article model
@article.comment_associations.joins(:comments).merge(Comment.for_title("given title"))

# Comment model
scope :for_title, -> title { where(title: title) }

基本上,如果您想要CommentAssociations,那么您必须从CommentAssociations开始进行查询。。。但是,您可以在其他关联模型的作用域中包含和合并这些模型。

谢谢,这很有效。在哪里可以找到有关
包括
合并
的更多信息?再次感谢。
order
子句是否可以合并?我甚至想按
评论的标题订购
asc
评论协会
。是否可以通过
包含
合并
?我没有尝试过,但可能是
。合并(Comment.for\u title(“给定标题”).by\u title\u asc)
,given
by\u title\u asc
是注释模型的另一个范围。顺便说一句:您应该
加入
(而不是
包含
)。