2013-04-10 69 views
1

我有一個集合非活動記錄模型,每個都有幾個外鍵。我想急切地加入協會,但我正在爲這種方法而努力。該代碼看起來是這樣的:渴望加載外活動記錄

型號:

class Tuple 
    attr_accessor :widget_id 
    attr_accessor :woogle_id 

    def self.all 
    # returns a bunch of tuples with ids 
    end 

    def widget 
    @widget ||= Widget.find(widget_id) 
    end 

    def woogle 
    @woogle ||= Woogle.find(woogle_id) 
    end 
end 

查看:

- Tuple.all.each do |tuple| 
    = render tuple.widget 
    = render tuple.woogle 

任何在這種情況下如何渴望負載活動記錄外,避免N + 1個查詢的想法?

+0

你用什麼來代替ActiveRecord?你的記錄如何存儲? – Substantial 2013-04-10 23:33:58

+0

@gg_s關聯的記錄由ActiveRecord支持(只有Tuple不支持Active Record) – 2013-04-11 02:42:56

回答

1

此代碼應該爲你工作,但如果有設置@woogle@widget實例變量更清潔的方式,將是很好:

def self.all 
    # get a bunch of tuples with ids 
    all_tuples = some_logic 
    widgets = Widget.where(id: all_tuples.map(&:widget_id)).inject({}){|m, w| m[w.id] = w; m} 
    woogles = Woogle.where(id: all_tuples.map(&:woogle_id)).inject({}){|m, w| m[w.id] = w; m} 
    all_tuples.each do |t| 
    t.instance_variable_set :@widget, widgets[t.widget_id] 
    t.instance_variable_set :@woogle, woogles[t.woogle_id] 
    end 
end 

需要注意的是,如果任何控件或Woogle協會的元組是相同,該關聯只有一個實例實際上是由相關元組加載並共享的