我使用Rails 5.1和PostgreSQL 9.5并且是Arel表的新手。我试图创建一个查询(我希望最终与其他范围查询链接),它返回所有相关记录与给定输入匹配的记录。
给定weekday_ids: [1, 2, 5, 6]
数组,仅返回ranges
,其中有效time_slots
匹配全部给定weekday_ids
模型
class Range < ApplicationRecord
has_many :time_slots
end
class TimeSlot < ApplicationRecord
belongs_to :range
belongs_to :weekday
end
返回预期结果的工作示例
def self.qualified_time_slots(weekday_ids = nil)
weekday_ids ||= [1, 2, 5, 6]
qualified_ranges = Range.includes(:time_slots).all.map do |range|
active_time_slots = range.time_slots.where(active: true)
range if weekday_ids.all? { |day| active_time_slots.map(&:weekday_id).include? day }
end
# return
qualified_ranges.compact
end
Arel Query目前的非工作尝试与上述方法相同
Range.joins(
:time_slots
).where(
time_slots: { active: true }
).where(
TimeSlot.arel_table[:weekday_id].in(weekday_ids)
)
预期结果
# Should return:
[
range: {
id: 1,
time_slots: [
{ weekday_id: 1 },
{ weekday_id: 2 },
{ weekday_id: 5 },
{ weekday_id: 6 },
]
},
range: {
id: 2,
time_slots: [
{ weekday_id: 0 },
{ weekday_id: 1 },
{ weekday_id: 2 },
{ weekday_id: 3 },
{ weekday_id: 4 },
{ weekday_id: 5 },
{ weekday_id: 6 },
]
}
]
# Should NOT return
[
range: {
id: 3,
time_slots: [
{ weekday_id: 1 },
{ weekday_id: 2 },
{ weekday_id: 5 },
]
},
range: {
id: 4,
time_slots: [
{ weekday_id: 0 },
{ weekday_id: 6 },
]
}
]
编辑 - 在这方面工作时,我已经按照Joe Celko article on Relational Division中的示例创建了这个原始SQL查询,该查询似乎有效但尚未完全下注测试:
ActiveRecord::Base.connection.exec_query("
SELECT
ts.range_id
FROM
time_slots AS ts
WHERE
ts.active = true
AND
ts.weekday_id IN (#{weekday_ids.join(',')})
GROUP BY
ts.range_id
HAVING COUNT(weekday_id) >= #{weekday_ids.length};
")
答案 0 :(得分:1)
我还在测试这个,但看起来这样可行:
Range.joins(
:time_slots
).where(
TimeSlot.arel_table[:active].eq(
true
).and(
TimeSlot.arel_table[:weekday_id].in(
weekday_ids
)
)
).group(
Range.arel_table[:id]
).having(
TimeSlot.arel_table[:weekday_id].count(true).gteq(weekday_ids.count)
)