我有一种情况,即构建子项但未保存,然后在引用父项的视图中使用。这导致大量使用轨道记录缓存。我想让父母'急切地加载'未保存的子记录。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