[英]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 在Person.rb中,我试图创建一种在一个查询中获取所有事件和表的方法
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]>]
I am able to iterate and create a all_events
object, but it not nested. 我能够迭代并创建all_events
对象,但它不是嵌套的。
def complete_events
all_events = []
events.includes(:tables).each do |event|
all_events << event
all_events << event.tables
end
all_events
end
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是Model,配置文件和address是具有has_many或has_one关联的映射表,因此将要呈现的json将以嵌套方式包含该表,如下所示
user : {
name:"dummy name",
profile: {},
addresses: {}
}
so in one single object you will have all the data and the associated data. 因此,在一个对象中,您将拥有所有数据和关联的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.