6

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

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

4

3 回答 3

13

不久前我遇到了这个问题,幸好有一个很好的解决方案。

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
于 2012-06-05T04:23:51.827 回答
1

@samuel 的这个答案正是我想要的,但我希望在通过 Taxon1 AND Taxon2 和 TaxonN 过滤时仍然能够为搜索提供关键字。我不需要进行 Taxon1 OR 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

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

于 2013-08-08T06:47:28.470 回答
0

假设性能不是要求:

a = Taxon.find_by_name!('Ruby on Rails').products.pluck(:id)
b = Taxon.find_by_name!('Shirts').products.where(:id => a)
于 2012-06-05T03:59:51.290 回答