I have two models, Facility and Category:
class Facility < ActiveRecord::Base has_and_belongs_to_many :categories end class Category < ActiveRecord::Base has_and_belongs_to_many :facilities end Say I have three possible Category records, with name: "Category A", "Category B", and "Category C".
I want to get all Facility records which are in both "Category A" and "Category B".
My latest query is:
Facility.joins(:categories).merge(Category.where(Category.arel_table[:name].matches_all(["Category A", "Category B"]))) which produces the following SQL:
SELECT "facilities".* FROM "facilities" INNER JOIN "categories_facilities" ON "categories_facilities"."facility_id" = "facilities"."id" INNER JOIN "categories" ON "categories"."id" = "categories_facilities"."category_id" WHERE ("categories"."name" ILIKE 'Category A' AND "categories"."name" ILIKE 'Category B') This returns no results.
Using pure Ruby (e.g. Facility.all.select ...), I know there is at least one Facility in the database which belongs to both and only both "Category A" and "Category B".
How can I perform this query either in Rails or using arel?