# 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
在Person.rb中我试图创建一个方法来在一个查询中获取所有事件和表
def complete_events
events.includes(:tables)
end
我可以在控制台中看到它正在加载事件和表
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)
但是,返回的对象只是事件记录。
#<ActiveRecord::Relation [#<Event id: 1, name: "some event">]
如何将返回的记录嵌套到下面?
#<ActiveRecord::Relation [#<Event id: 1, name: "some event", tables: [id: 1, seats: 4, id: 2, seats: 4]>]
我能够迭代并创建一个all_events
对象,但它没有嵌套。
def complete_events
all_events = []
events.includes(:tables).each do |event|
all_events << event
all_events << event.tables
end
all_events
end
答案 0 :(得分:3)
使用as_json
:
def complete_events
as_json(
include: {
events: {
include: tables
}
)
end
答案 1 :(得分:1)
试试这个。
User.all.as_json(methods:[:profile,:addresses])
此处用户是模型,配置文件和地址是具有has_many或has_one关联的映射表,因此将呈现的json将以嵌套方式包含表,如下所示
user : {
name:"dummy name",
profile: {},
addresses: {}
}
因此,在一个对象中,您将获得所有数据和相关数据。