我有以下内容:
class ObjectA < ActiveRecord::Base
has_one :object_b
end
class ObjectB < ActiveRecord::Base
belongs_to :object_a
has_one :object_c
end
class ObjectC < ActiveRecord::Base
belongs_to :object_b
end
因此,做ObjectA.eager_load(:object_b)会显着地加载ObjectB。 但是我每次打电话时都试图加载整个层次结构,而不必发出新的查询:object_a.object_b.object_c
想法?
答案 0 :(得分:2)
如果您执行类似
的操作ObjectA.includes(object_b: :object_c).where(...)
对于符合ObjectA
条件的每个ObjectB
,这会急切加载ObjectC
个相关ObjectA
和嵌套where(...)
。
如果您希望在需要执行热切加载时避免重复上述查询格式,可以在ObjectA
上创建一个类方法。
class ObjectA < ActiveRecord::Base
has_one :object_b
def self.with_related(conditions)
includes(object_b: :object_c).where(conditions)
end
end