Viacheslav Bobrov
Viacheslav Bobrov

Reputation: 11

Spree Taxons relations

Goal: show taxons from another taxanomy within taxon

What I have: Taxanomy1 'Categories' Taxons [Guitar, violin, piano] Taxanomy2 'Brands' Taxons [Yamaha, Samick, PROEL]

Product has both: category & brand

Task1: When Im on taxon show page, I want to show Brands that @products have

Task2: When Im on brands page, I want to show categories that current brand products have

Sorry, if my explanation isnt clear enough

Upvotes: 1

Views: 508

Answers (1)

phil pirozhkov
phil pirozhkov

Reputation: 4900

taxon_id = 558398765 # "Current" Taxon
brand_taxonomy_id = 854451436 # Your "Brand" Taxonomy
sql_query  = <<-SQL
SELECT DISTINCT "spree_products_taxons"."taxon_id" FROM "spree_products_taxons" WHERE "spree_products_taxons"."product_id" IN (
  SELECT "spree_products"."id" FROM "spree_products"
  INNER JOIN "spree_products_taxons" ON "spree_products"."id" = "spree_products_taxons"."product_id"
  WHERE "spree_products_taxons"."taxon_id" = #{taxon_id}
)
SQL
taxon_ids = ActiveRecord::Base.connection.execute(sql_query).to_a.map {|tp| tp['taxon_id']}
Taxon.where(id: taxon_ids, taxonomy_id: brand_taxonomy_id).all # All "Brand" taxons for all products in your "Current" Taxon

Same for Task2, change last row to:

Taxon.where(id: taxon_ids, taxonomy_id: category_taxonomy_id).all # All "Category" taxons for all products in your "Brand" Taxon

Upvotes: 1

Related Questions