2

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?

1 Answer 1

2

I was able to solve this with switching from a has_and_belongs_to_many to has_many, through, and the following scope on Facility:

joins(:categories) .merge(Category.where(key: category_keys)) .group(CategoriesFacility.arel_table[:facility_id], arel_table[:id]) .having(CategoriesFacility.arel_table[:facility_id].count.gteq(category_keys.size)) .uniq 

Ideally, I'd like to still use a HABTM table, but I prefer not to write raw SQL in my code.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.