我的应用程序中有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,其中它返回艺术家的数组,每个艺术家都有一个属性'专辑',其中它是每个艺术家的专辑数组,每个专辑都有一个属性歌曲,这是一个歌曲数组为每张专辑。喜欢这个
[ {
id: 1,
name: Artist_Name,
albums: [
{
id: 1,
name: Album_Name,
songs: [{
id: 1,
title: Song_Title,
lyrics: Song_Lyrics
}]
}
]
}]
答案 0 :(得分:2)
按照惯例,模型名称应该是单数,其次你最后的模型名称应该是歌曲。
在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}})
答案 1 :(得分:1)
我建议你使用Jbuilder gem https://github.com/rails/jbuilder