我遇到了通过多个条件从数据库获取行的问题。
我有一个表 Slot 和 SlotAlteration。
该时段有一个 time_off_id 字段。
SlotAlteration 有两列,slot_id 和 action。 Action 可以是 0 或 1。每个槽在 SlotAlteration 表中最多可以有两个条目,其中操作为 0 和 1(不是 0 和 0,也不是 1 和 1),或者根本没有与 SlotAlteration 的连接。
我需要转换成rails范围的查询是
select *
from Slot s
where time_off_id is null
and not exists (select 1 from Alterr a where s.id = a.slot_id and a.action = 1)
Alterr 是 SlotAlteration 表
这是可视化表示的 SQL 结构和查询。
我的插槽模型有关联
has_many :alterations
scope :free, -> {
left_joins(:alterations)
.where(time_off_id: nil)
.where.not(alterations: { action: 1 })
}
我尝试过,但这不是没有更改的精选插槽
如果您共享在您编写的范围内生成的相应 SQL 查询,那么调试将很容易。
如果要包含非空值,您还可以通过在查询中选择非空值以及 !=1 来验证这一点。
这可能对你有帮助。
使用where子句而不是where!并包括 null 。
scope :free, -> {
left_joins(:alterations)
.where(time_off_id: nil)
.where("alterations.id IS NULL OR alterations.action != ?", 1)
}