我的RoR应用程序(一个JSON API)中有一组代表运动队的“玩家”和“团队”模型,其中“名册”模型充当了多对多关系中的中间人。在“名单”视图中,我试图通过团队用jbuilder对玩家进行“分组”,但我无法找到正确的代码来执行此操作。
我当前的jbuilder视图代码(index.json.jbuilder)如下所示:
json.rosters @rosters do |roster|
json.team_id roster.team.team_id
json.team_name roster.team.team_name
json.player_id roster.player.player_id
json.first_name roster.player.first_name
json.last_name roster.player.last_name
end
这会输出以下JSON:
{
"rosters": [
{
"team_id": "1",
"team_name": "Dallas Mavericks",
"player_id": "1",
"first_name": "Dirk",
"last_name": "Nowitzki"
},
{
"team_id": "1",
"team_name": "Dallas Mavericks",
"player_id": "2",
"first_name": "Rajon",
"last_name": "Rando"
}
]
}
我的问题:如何让jbuilder以这种格式输出数据? :
{
"rosters": [
{
"team_id": "1",
"team_name": "Dallas Mavericks",
"players": [
{
"player_id": "1",
"first_name": "Dirk",
"last_name": "Nowitzki"
},
{
"player_id": "2",
"first_name": "Rajon",
"last_name": "Rando"
}
]
}
]
}
一些旁注: