我有两种型号,Facility
和Category
:
class Facility < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :facilities
end
说我有三个可能的 Category
记录,带有 name
:"类别A","类别B"one_answers"类别C"。
我想获得所有"类别A"one_answers"类别B"的Facility
记录。
我的最新查询是:
Facility.joins(:categories).merge(Category.where(Category.arel_table[:name].matches_all(["Category A", "Category B"])))
产生以下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')
这返回没有结果。
使用Pure Ruby(例如Facility.all.select ...
),我知道数据库中至少有一个Facility
属于两者,并且仅属于"类别A"one_answers"类别B"。
如何在铁轨或使用Arel?
我能够通过从 has_and_belongs_to_many
切换到 has_many, through
来解决此问题,以及在 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
理想情况下,我仍然想使用HABTM表,但是我不想在代码中写下RAW SQL。