我有一種情況,即構建子項但未保存,然後在引用父項的視圖中使用。這導致大量使用軌道記錄緩存。我想讓父母'急切地加載'未保存的子記錄。Rails ActiveRecord - 使用has_many中的'build'時急切加載(有點)
class Parent < ActiveRecord::Base
has_many :children
def make_children
loop..
children_array << children.build(...)
end
end
end
然後在視圖(請注意,「孩子」不保存到DB):
children_array.each do |child|
# What's the best way to optimise this so it doesn't
# keep selecting parent albeit from the cache?
child.parent
end
注意:我已經使用術語eager加載在這裏來表明我在做什麼之後,雖然我知道在這種情況下,加載並不可能,因爲它不是從DB獲取的,因此不能使用連接像渴望加載通常一樣。 – 2009-12-08 19:40:11