Rails - Nested includes on Active Records?

I have a list of events that I fetch. I'm trying to include every user associated to this event and every profile associated to each user. The Users get included but not their profiles.

How Would i do this

Event.includes(:users [{profile:}])

The docs don't seem to be clear: http://guides.rubyonrails.org/active_record_querying.html


Solution 1:

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)

Solution 2:

Please refer to Joe Kennedy's solution.

Here's a more readable example (for future me).

includes(
  :product,
  :package, {
    campaign: [
      :external_records,
      { account: [:external_records] },
      { agency: [:external_records] },
      :owner,
      :partner,
    ]
  }
)