Rails - Nested includes on Active Records?

Ruby on-RailsRails Activerecord

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaryaxtView Question on Stackoverflow
Solution 1 - Ruby on-RailsJoe KennedyView Answer on Stackoverflow
Solution 2 - Ruby on-RailsaschyielView Answer on Stackoverflow
Solution 3 - Ruby on-RailsBlaskoviczView Answer on Stackoverflow