0

I have the following:

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

So doing ObjectA.eager_load(:object_b) will eager load the ObjectB obviously. But i'm trying to eager load the entire hierarchy without having to issue a new query every time I call: object_a.object_b.object_c

Ideas?

Yoni
  • 624
  • 5
  • 15

1 Answers1

2

If you do something like

ObjectA.includes(object_b: :object_c).where(...)

This will eager load ObjectA's related ObjectB and the nested ObjectC for each ObjectA matching the where(...) conditions.

If you're looking to avoid duplicating the above query format whenever you want to do the eager load, you could make a class method on ObjectA.

class ObjectA < ActiveRecord::Base
  has_one   :object_b

  def self.with_related(conditions)
    includes(object_b: :object_c).where(conditions)
  end
end

Reference: Eager Loading of Associations

deefour
  • 34,974
  • 7
  • 97
  • 90