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 any 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 :
adding an inner join and one and clause for every category.
There is other queries possibles, this one should perform well in MySQL.