【发布时间】:2019-05-24 11:54:13
【问题描述】:
我的系统有以下型号
class Application < ApplicationRecord
has_many :offers, dependent: :destroy
belongs_to :accepted_offer, class_name: 'Offer',
foreign_key: 'accepted_offer_id',
optional: true
class Offer < ApplicationRecord
belongs_to :application
并且正在创建一个报告,收集accepted_offer_id 的所有报价,就像这样
Application.find_each do |app|
offer = Offer.find(app.accepted_offer_id) if app.accepted_offer_id
report.push(report_body(app, offer))
end
这变得太慢了,我想重写报告位,以便它利用左连接来与数据库的单查询建立连接。
我想让查询返回以accepted_offer_id 形式存储在应用程序表上的所有优惠。
Offer.left_outer_joins(:applications).where(id: { 'application.accetped_offer_id' })
我知道上面的内容是错误的,但我确定必须可以通过单个查询获取集合?
【问题讨论】:
-
试试
.where("application.accetped_offer_id IS NOT NULL")
标签: ruby-on-rails postgresql left-join