【发布时间】: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