Ruby on rails 如何搜索关联记录具有给定属性值的关联?
我正在使用RubyonRails4,我想搜索关联记录,其中关联记录具有给定的属性值。也就是说,我有一个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 类文章
有很多:通过像下面这样的关联
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)
,givenby\u title\u asc
是注释模型的另一个范围。顺便说一句:您应该加入(而不是包含)。