我们的rails应用中有3个表payment_logs
,sourcings
和purchasings
。 payment_log属于采购或采购,但不属于同时。采购和采购都有一个col project_id
。我们想要选择all payment_logs with its project_id = project_id_search
(从搜索页面传递的project_id_search)。我们还需要一个ActiveRecord作为返回的结果集。以下是单个查询,假设payment_logs包含ActiveRecord结果集:
选择所有payment_logs及其采购的project_id = project_id_search
payment_logs = payment_logs.joins(:sourcing).where(“sourcings.project_id =?”,project_id_search)
选择所有payment_logs及其购买的project_id = project_id_search
payment_logs = payment_logs。(:purchase).where(“purchasings.project_id =?”,project_id_search)
我们需要联合1和2以获取其project_id = project_id_search的所有payment_log。什么是完成它的正确方法?我们没有在rails中找到union,find_by_sql返回的数组不是我们想要的。感谢。
答案 0 :(得分:1)
payment_logs.where(["
payment_logs.sourcing_id IN (
SELECT id FROM sourcings WHERE sourcings.project_id = ?
)
OR payment_logs.purchasing_id IN
(
SELECT id FROM purchasings WHERE purchasings.project_id = ?
)", project_id_search, project_id_search])
很多SQL,但它应该可以工作
选项2(两个SQL请求......):
payment_logs = []
payment_logs << PaymentLog.joins(:sourcing).where("sourcings.project_id" => project_id_search)
payment_logs << PaymentLog.joins(:purchasing).where("purchasings.project_id" => project_id_search)
payment_logs.uniq! #In case some records have both a sourcing and a purchasing
选项3,使用squeel
gem:https://github.com/ernie/squeel
PaymentLog.where{(source_id.in Sourcing.where(:project_id => project_id_search)) | (purchasing_id.in Purchasing.where(:project_id => project_id_search))}
我喜欢这个解决方案:) 此外,只要您对生成的SQL有疑问,从控制台或其他任何地方,您可以在ActiveRecord查询结束时添加.to_sql以双重检查生成的SQL