Search code examples
sqlruby-on-railsspreehas-many

Find all Products by Tag in Rails with ActiveRecord


This is probably something very simple but I'm looking for the optimal way of retrieving all Products by Tag, so to speak. This is with Spree, so I should stick to the way they have modeled their data. It's actually Product and Taxon (like category, brand, etc.)

So if Product has_and_belongs_to_many :taxons and Taxon has_and_belongs_to_many :products, what's the best way to find all products by a Taxon?

Something like:

@taxon = Taxon.find_by_permalink('categories/')
@products = Product.find_by_taxon(@taxon)

... but I'm not sure what goes into that last method (just made up the name).


Solution

  • Probably you're going to just simply say if there's only one Taxon

    @products = @taxon.products
    

    If there's multiple we require a slightly different method. But even then you could just

    @products = @taxons.inject([]) {|taxon| taxon.products}