Order has_many TypeLogistic
但重要的是...... Order
无法拥有TypeLogistic
。 Order
和& TypeLogistic
具有status_id
属性。我想找到所有uniq Order
记录,其中:
order.status_id = 4
,如果未满足此主要条件,则忽略有关儿童的任何内容order
确实有孩子type_logistics
,那么所有子type_logistics
必须有status_id
1或2(不是任何其他数字而不是{ {1}})换句话说......这些是可以找到的记录
null
这些是无法找到的记录
Order
status_id = 4
TypeLogistics
1 - status_id = 1
Order
status_id = 4
TypeLogistics
1 - status_id = 2
Order
status_id = 4
TypeLogistics
1 - status_id = 1
2 - status_id = 2
Order
status_id = 4
我编写了一段可行的代码,但它很笨重,因为它使用# because order.status_id != 4
Order
status_id = 1
TypeLogistics
1 - status_id = 1
# because type_logistic child does not have a status_id that's 1 or 2
Order
status_id = 4
TypeLogistics
1 - status_id = nil
# because type_logistic child does not have a status_id that's 1 or 2
Order
status_id = 4
TypeLogistics
1 - status_id = 3
# because not all type_logistic children have a status_id that's 1 or 2
Order
status_id = 4
TypeLogistics
1 - status_id = 1
2 - status_id = nil
# because not all type_logistic children have a status_id that's 1 or 2
Order
status_id = 4
TypeLogistics
1 - status_id = 2
2 - status_id = 3
而非纯select
查询。救救我?
工作,SUB-PAR代码
where
答案 0 :(得分:0)
使用joins
可以查询已加入的关联。 preload
将急切加载type_logistics(如果存在满足where("type_logistics.status_id IN ( ? )", [1,2])
查询中指定的条件。 preload
的行为大多与includes
相似。
@orders = Order.joins(:type_logistics).preload(:type_logistics).where("orders.status_id = ?", 4).where("type_logistics.status_id IN ( ? )", [1,2]).uniq