【发布时间】:2019-04-11 18:33:53
【问题描述】:
我需要找到所有具有状态 = 1 的孩子的父母。
如果其中一个孩子不是status = 1;则未选择父级。
class Parent
has_many :children
end
class Child
status = [ 0, 1 ]
end
这个我试过了,还是不行。
Parent.left_outer_joins(:children).where("children.status = ?", 1)
它不起作用,因为我仍然得到 Parent with children status=0
【问题讨论】:
-
it doesn't work.是什么意思您在查询时遇到任何错误或问题吗? -
@Gabbar 它不起作用,因为我仍然得到 Parent with children status=0
-
是
status枚举? -
@Gabbar 是的,它是枚举
-
我猜在你的情况下加入是不够的。 “所有孩子的状态为 1”等价于“没有状态为 0 的孩子”。因此,您需要像
select * from parents p where not exists (select 1 from children c where c.parent_id = p.id and status = 0)这样的查询——不确定是否可以使用 AR 查询界面构建它。 AREL 魔法可能会有所帮助,但老实说,在实践中我更喜欢纯 SQL - 因为更具可读性和直截了当......
标签: ruby-on-rails ruby activerecord