Search code examples
ruby-on-railsspree

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!.


Solution

  • 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