baconck
baconck

Reputation: 406

Include nested associations in JSON

# Person.rb
class Person < ActiveRecord::Base
  has_many :events
end

# Event.rb
class Event < ActiveRecord::Base
  belongs_to :person
  has_many :tables
end

# Table.rb
class Table < ActiveRecord::Base
  belongs_to :event
end

Within Person.rb I am trying to create a method to get all events and tables in one query

def complete_events
  events.includes(:tables)
end

I can see in the console it is loading both events and table

  Event Load (1.1ms)  SELECT "events".* FROM "events" WHERE "event"."person_id" = $1  [["person_id", 17]]
  Table Load (0.5ms)  SELECT "tables".* FROM "tables" WHERE "tables"."event_id" IN (10)

However, the returned object is only the event records.

#<ActiveRecord::Relation [#<Event id: 1, name: "some event">]

How can I get the returned record to nested like below?

#<ActiveRecord::Relation [#<Event id: 1, name: "some event", tables: [id: 1, seats: 4, id: 2, seats: 4]>]

Edit

I am able to iterate and create a all_events object, but it not nested.

  def complete_events
    all_events = []
    events.includes(:tables).each do |event|
      all_events << event
      all_events << event.tables
    end
    all_events
  end

Upvotes: 2

Views: 2662

Answers (2)

Apoorv
Apoorv

Reputation: 1389

try this.

  User.all.as_json(methods:[:profile,:addresses])

here User is the Model, and profile and address are the mapped table having has_many or has_one associations , so the json that will be rendered will be containing the table in nested way as follows

user : {
name:"dummy name",
     profile: {},
     addresses: {}
}

so in one single object you will have all the data and the associated data.

Upvotes: 1

potashin
potashin

Reputation: 44581

Use as_json:

def complete_events
 as_json(
   include: {
     events: {
       include: tables
   }
 )
end

Upvotes: 4

Related Questions