0

有 3 个表payment_logs,在我们sourcingspurchasingsrails 应用程序中。payment_log 属于采购或采购,但不能同时属于两者。采购和采购都有一个col project_id。我们要提取all payment_logs with its project_id = project_id_search(从搜索页面传递的 project_id_search)。我们还需要一个 ActiveRecord 作为返回的结果集。这是单个查询,假设 payment_logs 保存 ActiveRecord 结果集:

  1. 使用其采购的 project_id = project_id_search 选择所有 payment_logs

    payment_logs = payment_logs.joins(:sourcing).where("sourcing.project_id = ?", project_id_search)

  2. 使用其购买的 project_id = project_id_search 选择所有 payment_logs

    payment_logs = payment_logs.(:purchasing).where("purchasings.project_id = ?", project_id_search)

我们需要联合 1 和 2 以获取所有 project_id = project_id_search 的 payment_logs。实现它的正确方法是什么?我们没有在 rails 中找到 union 并且 find_by_sql 返回了一个不是我们想要的数组。谢谢。

4

1 回答 1

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,使用squeelgem: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

于 2012-07-30T19:40:36.913 回答