[英]rails fetch records with no has many relationship and ones with a condition
I have a HomeMaker
and PerDateUnavailability
models. 我有一个HomeMaker
和PerDateUnavailability
模型。 HomeMaker
has_many per_date_unavailabilities
. HomeMaker
has_many per_date_unavailabilities
。 I want all home makers who don't have a record in per_date_unavailabilities and home makers who have record but not when the per_date_unavailabilties.unavailable_date
= somedate 我希望所有在per_date_unavailability中没有记录的房屋制造商以及在没有per_date_unavailabilties.unavailable_date
= somedate时有记录但没有记录的房屋制造商
I usually do the first part when I want HomeMakers without a PerDateUnavailability record using HomeMaker.includes(:per_date_unavailabilities).where(per_date_unavailabilities: {id: nil})
当我要使用HomeMaker.includes(:per_date_unavailabilities).where(per_date_unavailabilities: {id: nil})
而不需要PerDateUnavailability记录的HomeMakers时,通常会做第一部分。其中HomeMaker.includes(:per_date_unavailabilities).where(per_date_unavailabilities: {id: nil})
and the second part of the condition using HomeMaker.joins(:per_date_unavailabilities).where.not(per_date_unavailabilities: {unavailable_date: Date.today})
第二部分条件使用HomeMaker.joins(:per_date_unavailabilities).where.not(per_date_unavailabilities: {unavailable_date: Date.today})
How do I mix these? 如何混合这些?
The sql you need is somewhat like this: 您需要的sql如下所示:
select a.*
from home_makers a left join per_date_unavailabilities b
on a.id = b.home_maker_id
where b.home_maker_id is NULL
or b.unavailable_date IS NOT ?;
Expressing the or
clause is a little tough in ActiveRecord, and its best we don't fight it. 在ActiveRecord中,表达or
子句有点困难,最好不要与之抗争。 (Edited after OP's comment) (在OP评论后编辑)
HomeMaker.joins("LEFT JOIN per_date_unavailabilities on per_date_unavailabilities.home_maker_id = home_makers.id")
.where("per_date_unavailabilities.home_maker_id IS NULL OR per_date_unavailabilities.unavailable_date != ?", somedate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.