开发者

AR 3 scope on HBTM relation to retrieve elements that matches all IDs

开发者 https://www.devze.com 2023-03-16 18:05 出处:网络
OK, the title is not that good... Here is the example : class Product has_and_belongs_to_many :categories

OK, the title is not that good...

Here is the example :

class Product
  has_and_belongs_to_many :categories
end

I want to create a scope that returns Products that have ALL the categories IDs I've sent as argument.

If I use Product.includes(:categories).where(:"categories.categorie_id" => [1,2,3,4]) it gives me all Products that have a开发者_Python百科ny of categories 1, 2, 3, 4. I would like Products which have at least all the categories I send as parameter.

For example :

Product.with_all_categories([1, 2, 3, 4]) # => get all the Product that have categories 1, 2, 3 AND 4 (at least, it could be more).


I guess you won't like the answer : this is not easy.

AFAIK, it's not something you can do in AR directly. You have to go through find_by_sql. The request you need is something like :

SELECT products.* FROM products
INNER JOIN categories_products cat1 ON products.id = 
cat1.product_id
INNER JOIN categories_products cat2 ON products.id = 
cat2.product_id
INNER JOIN categories_products cat3 ON products.id = 
cat3.product_id
WHERE (cat1.category_id = 1) and (cat3.category_id = 2) and (cat3.category_id = 3)

adding an inner join and one and clause for every category. There is other queries possibles, this one should perform well in MySQL.


Thanks @tal !

Here is my implementation of your solution in pure scopable AR : https://gist.github.com/1071862

:)

0

精彩评论

暂无评论...
验证码 换一张
取 消