在另一个表中查找具有两个特定记录的记录

我有一个Product型号has_and_belongs_to_many :taxons ,我想找到特定分类中的所有产品。

例如,如果产品同时属于“Ruby on Rails”和“Shirts”分类,我希望在数据集中返回该产品,但是如果它只属于“Ruby on Rails”或“Shirts”

我曾经有过这个问题,谢天谢地,有一个很好的解决方案。

 def self.has_taxons(taxons) id = arel_table[:id] Product.joins(:taxons).where(taxons: { name: taxons }).group(id).having(id.count.eq(taxons.size)) end 

来自@samuel的答案正是我所寻找的,但我希望能够在按Taxon1和Taxon2以及TaxonN过滤时仍然为搜索提供关键字。 我不需要进行Taxon1或Taxon2搜索,因此我进行了以下自定义。 可能有一种不太常见的方法,但它对我来说很有用。

我在/app/models/spree/product_decorator.rb中添加了一个新的产品范围

 Spree::Product.class_eval do add_search_scope :in_all_taxons do |*taxons| taxons = get_taxons(taxons) id = arel_table[:id] joins(:taxons).where(spree_taxons: { id: taxons }).group(id).having(id.count.eq(taxons.size)) end end 

然后通过将新范围添加到/app/models/spree/base_decorator.rb来使用新范围

 Spree::Core::Search::Base.class_eval do def get_base_scope base_scope = Spree::Product.active base_scope = base_scope.in_all_taxons(taxon) unless taxon.blank? base_scope = get_products_conditions_for(base_scope, keywords) base_scope = add_search_scopes(base_scope) base_scope end end 

现在我可以使用标准搜索助手来检索产品(这意味着我仍然可以提供关键字等以及多个分类):

 # taxon_ids is an array of taxon ids @searcher = build_searcher(params.merge(:taxon => taxon_ids)) @products = @searcher.retrieve_products 

这适合我,感觉很轻松。 但是,我愿意接受更好的选择。

假设性能不是必需的:

 a = Taxon.find_by_name!('Ruby on Rails').products.pluck(:id) b = Taxon.find_by_name!('Shirts').products.where(:id => a)