我的应用程序中有 3 个模型 艺术家、专辑和歌曲
class Artist < ActiveRecord::Base
has_many :albums
has_many :songs, :through => :albums
end
class Albums < ActiveRecord::Base
has_many :songs
belongs_to :artist
end
class Albums < ActiveRecord::Base
belongs_to :albums
end
如何将其渲染为 JSON,其中它返回艺术家的数组,每个艺术家都有一个属性“Albums”,其中它是每个艺术家的专辑数组,每个专辑都有一个属性 Songs,它是歌曲数组每张专辑。像这样
[ {
id: 1,
name: Artist_Name,
albums: [
{
id: 1,
name: Album_Name,
songs: [{
id: 1,
title: Song_Title,
lyrics: Song_Lyrics
}]
}
]
}]
最佳答案
根据 Rails 约定,模型名称应该是单数,其次你的最后一个模型名称应该是 Song。
要在 Json 中包含嵌套的关联资源,请像这样定义模型:
class Artist < ActiveRecord::Base
has_many :albums
has_many :songs, :through => :albums
def as_json(options={})
super(include: { albums: { include: :songs } })
end
end
class Album < ActiveRecord::Base
has_many :songs
belongs_to :artist
end
class Song < ActiveRecord::Base
belongs_to :album
end
现在,在您的事件唱片艺术家对象上调用 .to_json
将返回嵌套的专辑和歌曲。
或者你可以直接调用它Artist.all.to_json(include: {albums: {include: :songs}})
关于ruby-on-rails - Rails 通过关联渲染 has_many 的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37096256/