# 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
Copyright Notice:Content Author:「baconck」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40454785/include-nested-associations-in-json