baconck baconck - 29 days ago 14
Ruby Question

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

Answer

Use as_json:

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