3

i have a product model and a product category model. and theres a habtm between those.

i have categories like 'men' and 'jeans' and i would like to filter these. to do a filter on men is no problem but i need to filter multiple parameters (men and jeans). i tried some variations but i'm stuck on this.

this is what i have so far..

Product.joins(:product_categories).where(['product_categories.id = 5 and product_categories.id = 6'])

thanks for your time!

Oliver
  • 801
  • 13
  • 26

2 Answers2

3

How about writting it like this and passing array of ids you're looking to filter by?

Product.joins(:product_categories).where(['product_categories.id in (?)', _product_categories_ids ])
socjopata
  • 5,028
  • 3
  • 30
  • 33
  • 1
    hm i figured out that this doesnt solve my problem.. if i select men and jeans.. i dont want women jeans.. this is what happens with the code above.. IN is like OR.. right? i need AND.. how i can achive this? thanks – Oliver Oct 10 '11 at 08:15
2

this is the solution which selects men AND jeans and not men OR jeans:

@products = Product.scoped

@product_category_ids.each.with_index do |product_category_id, index|
  @products = @products.joins("INNER JOIN product_categories_products pcp#{index} ON pcp#{index}.product_id = products.id AND pcp#{index}.product_category_id = #{product_category_id}")
end
Oliver
  • 801
  • 13
  • 26