2012-10-23 29 views
0

我有這兩個相關的ActiveRecord模型:左外與範圍捧場的ActiveRecord

class Channel < ActiveRecord::Base 
    has_many :events 
end 

class Event < ActiveRecord::Base 
    belongs_to :channel 

    def self.current 
    now = Time.now.utc 
    where{(starts_at<=now)&(ends_at>=now)} 
    end 
end 

我想要得到的Channel秒的清單,結合時事。對於個人Channel對象,我管理由下面的代碼來做到這一點:

> channel = Channel.first 
> channel.events.current 

它完美的作品。然而,我發現沒有辦法獲得Channel與他們的當前事件的集合,沒有觸及N + 1查詢問題。

回答

0

嘗試

channels = Channel.include(:events).all 
    channels.events.current