Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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,
    ]
  }
)

If anyone is doing a respond_to block to generate nested json, you can do something like:

respond_to do |f|
  f.json do
    render json: event.to_json(include: {users: {include: :profile} }), status: :ok
  end
end