Rails – Nested includes on Active Records?

I believe the following should work for you.

Event.includes(users: :profile)

If you want to include an association (we’ll call it C) of an already included association (we’ll call it B), you’d use the syntax above. However, if you’d like to include D as well, which is also an association of B, that’s when you’d use the array as given in the example in the Rails Guide.

A.includes(bees: [
  :cees, 
  :dees
])

You could continue to nest includes like that (if you actually need to). Say that A is also associated with Z, and that C is associated to E and F.

A.includes({
  bees: [{
    cees: [:ees, :effs]
  }, :dees]
}, :zees)

And for good fun, we’ll also say that E is associated to J and X, and that D is associated to Y.

A.includes({
  bees: [{
      cees: [{
        ees: [:jays, :exes]
      }, :effs]
    },
    {
      dees: :wise
    }
  ]
}, :zees)

Leave a Comment