【问题标题】:Eager Load without a formal ActiveRecord association没有正式的 ActiveRecord 关联的 Eager Load
【发布时间】:2016-08-06 03:23:34
【问题描述】:

我有一个 Record 类和 Pay Period 类,每个类都有一个 start_time 和 end_time。

我正在使用

获取一系列记录
Record.where(start_time: s..e)

我遇到了 N+1 查询问题,因为当我遍历这些记录时,我会查询它的支付周期。支付周期不能重叠,因此记录可以有一个或没有支付周期;但它们没有通过任何编码的 Active Record 关联链接到 Record。我对查找付款期的查询:

PayPeriod.where(%q{ (start_time, end_time) OVERLAPS (?, ?) }, self.start_time, self.end_time).first

类:

class Record < ActiveRecord::Base
   ...
   validates :start_time, presence: true
   validates :end_time, presence: true
   ...
end    


class PayPeriod < ActiveRecord::Base
   ...
   validates :start_time, presence: true
   validates :end_time, presence: true
   ...
end

我知道我需要使用记录预加载 PayPeriods。我真的很挣扎如何做到这一点。

【问题讨论】:

  • paypriods 和记录之间的关联是什么

标签: ruby-on-rails ruby activerecord eager-loading


【解决方案1】:

您始终可以使用纯 SQL 作为 where 方法的参数。请注意,表名通常是复数。

我猜Record 有很多PayPeriods 那么它可能看起来像:

Record.where(start_time: (start_time..end_time))
      .joins(pay_periods)
      .where('(pay_periods.start_time, pay_periods.end_time) OVERLAPS (records.start_time, records.end_time)')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2018-09-08
    • 2014-12-19
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多