2016-08-06 2 views
0

나는 Record 클래스와 Pay Period 클래스를 가지고 있는데, 각각 start_time과 end_time이있다.Eager 정식 ActiveRecord 연결이없는로드

나는

Record.where(start_time: s..e) 

를 사용하여 기록의 범위를 잡는거야 내가 N + 1 쿼리 문제로 실행 그것 때문에 지불 기간이기 위해 내가 루프가이 기록을 통해, 내가 쿼리를 수행 할 때. 유료 기간은 중복 될 수 없으므로 유료 기간에는 유료 기간이 하나 또는 없을 수 있습니다. 그러나 이들은 코딩 된 Active Record Association과 함께 Record에 링크되어 있지 않습니다. 수령액 기간을 찾는 내 쿼리 :

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

클래스 : 나는 레코드와 PayPeriods를 미리로드 할 필요가 알고

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 

. 나는 그것을하는 방법에 정말로 고심하고있다.

+0

뭐죠 paypriods과 기록 사이의 연관 –

답변

0

항상 where 메서드에 대한 인수로 일반 SQL을 사용할 수 있습니다. 테이블 이름은 대개 복수형입니다.

나는 그것을 볼 수있는 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)')