简体   繁体   English

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

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

I have the following structure in spree: 我疯狂地具有以下结构:

  • Taxon a 分类单元
    • Taxon a.1 分类单元a.1
      • Taxon a.1.1 分类单元a.1.1
        • Product 1 产品1
        • Product 2 产品2
        • Product 3 产品3

I need to know if there is a optimal way to list all the taxons of the products including the parents. 我需要知道是否有一种最佳方法来列出产品(包括父母)的所有分类单元。

Thanks!. 谢谢!。

I found a good approach in the following post: Spree: intersection between taxons 我在以下帖子中找到了一种很好的方法: 狂欢:分类单元之间的交集

Adding a search scope to the prodcut model: 将搜索范围添加到产品模型:

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

Then: 然后:

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

Will list all the products inside the referred taxon. 将列出所提及分类单元内的所有产品。

If you want to list the taxons a product belongs to (I'm not clear if that's what you're after), an option is to take advantage of helper methods in the acts_as_nested_set functionality that Spree uses for hierarchical taxons. 如果要列出产品所属的分类单元(我不清楚这是否是您想要的),一种选择是利用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"]

Have a look at all the methods available for nested sets for other ideas of how you can do this and similar things: https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet 看看嵌套集可用的所有方法,以获取有关如何执行此操作和类似操作的其他想法: https : //github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM