简体   繁体   中英

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
      • Taxon a.1.1
        • Product 1
        • Product 2
        • Product 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'))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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