[英]Rails 4 query records where nested has_many is empty
Working in Rails 4. 在Rails中工作4。
CompensationRecipient --has_many--> Compensations --has_many--> Payment CompensationRecipient --has_many->赔偿金--has_many->付款
So: 所以:
class CompensationRecipient
has_many :compensations
end
class Compensation
has_many :payments
belongs_to :compensation_recipient
end
class Payment
belongs_to :compensation
end
I want to get all the compensation recipients who's compensations have no payments on them. 我想让所有没有付款的补偿接受者。 It seems like it should not be very difficault, but I've not found the solution.
似乎应该不是很难,但是我没有找到解决方案。
something like this: 像这样的东西:
CompensationRecipient.includes(compensations: :payments).where(compensations: { payments: { id: nil }} )
That's not working however: PG::UndefinedColumn: ERROR: column compensations.compensation_id does not exist
但是,这是行不通的:
PG::UndefinedColumn: ERROR: column compensations.compensation_id does not exist
It is true, that column does not exist. 的确,该列不存在。 I don't understand why this query expects it though.
我不明白为什么这个查询期望它。
You need left outer join in this case. 在这种情况下,您需要左外部联接。 There is no special method for this in rails 4 (in rails 5 we have
left_joins
), but you could pass chunk of sql in joins
method. 在rails 4中没有特殊的方法(在rails 5中,我们有
left_joins
),但是您可以在joins
方法中传递sql块。
CompensationRecipient
.joins("LEFT JOIN compensations ON compensations.compensation_recipient_id = compensation_recipient.id")
.joins("LEFT JOIN payments ON payments.compensation_id = compensations.id")
.where(payments: { id: nil })
UPD: The first join should be inner though, because you don't want recipients without compensations at all, right? UPD:不过,第一次加入应该是内部的,因为您根本不希望接收者没有补偿,对吗?
CompensationRecipient
.joins(:compensations)
.joins("LEFT JOIN payments ON payments.compensation_id = compensations.id")
.where(payments: { id: nil })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.