Rails 4急切地在模型中加载模型

时间:2014-11-10 17:51:41

标签: activerecord ruby-on-rails-4 eager-loading

我有以下内容:

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

想法?

1 个答案:

答案 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

参考: Eager Loading of Associations