Rails、Spree:如何检查产品是否属于父类别

Rails, Spree: How to check if a product belongs to a parent category

我的spree结构如下:

我想知道是否有最佳的方式来列出包括亲本在内的产品的所有分类单元。

谢谢!

我在下面找到了一个很好的方法post:Spree: intersection between taxons

向产品模型添加搜索范围:

add_search_scope :in_taxon do |taxon|
  Spree::Product.joins(:taxons).where(Taxon.table_name => { :id => taxon.id }).
  order("spree_products_taxons.position ASC")
end

然后:

Spree::Product.all.in_taxon(Spree::Taxon.find_by_name('Taxon a'))

将列出所引用分类单元内的所有产品。

如果您想列出产品所属的分类单元(我不清楚这是否是您想要的),一个选项是利用 Spree 的 acts_as_nested_set 功能中的辅助方法用于分级分类单元。

product = Spree::Product.includes(:taxons).find_by(slug: 'gift-card')
product.taxons.map { |taxon| taxon.self_and_ancestors.map(&:name).join(' > ') }

=> ["Christmas Promotions > Last Minute > Gift Cards", "Digital Products > Gift Cards"]

查看可用于嵌套集的所有方法,了解如何执行此操作和类似操作的其他想法:https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet