Rails Nested Eager Loading?

196 Views Asked by At

Lets say we have a nested set up where

class Foo
  belongs_to :object
  has_many :bar
end

class Bar
  belongs_to :foo
  has_one :abc
end

class Abc
  belongs_to :bar
end

And I want to eager load abc from foo. What would be the best way to do this? Currently this doesn't seem to work:

object.foos(include: {bar: :abc})

My goal is to avoid making code like this:

object.foos.any? do |f|
  f.bar.abc.method_1 && f.bar.abc.method_2 && f.bar.abc.method_3
end

And move to more dry code like:

object.foos(rails_magic).any? do |x|
  x.method_1 && x.method_2 && x.method_3
end
1

There are 1 best solutions below

0
On

Because you can't do nested eager loading on anything other than a class, it makes sense to rearrange your query like so:

Foo.includes(:object, :bar => :abc).where('object_id = ?', object.id).references(:object).each do |f|
...
end

That query is eager-loading Object, as well as loading ABC through its own association to Bar.