Vote count:
0
I've got a set of "player" and "team" models in my RoR app (a JSON API) representing a sports team, with a "roster" model acting as the middleman in a many-to-many relationship. In the "roster" view, I'm trying to 'group' the players by team with jbuilder, but I can't figure out the proper code to do this.
My current jbuilder view code (index.json.jbuilder) looks like this:
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
This outputs the following 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"
}
]
}
My question: how can I get jbuilder to output the data in this format instead? :
{
"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"
}
]
}
]
}
Some side notes:
- For those wondering why the team-player relation is many-to-many, it's because players are allowed to change teams. The roster table has start- and end-date fields that represent a player's tenure on the team, representing a changing roster over time; this isn't shown in the above example for lack-of-clutter's sake.
- I could probably do this more easily in the Team view, but I don't want to return roster information there since it's primarily used for listing teams. Might end up being be a lot of data to unconditionally pull if I include the roster stuff each time.
- I'm using Sequel as my ORM, not ActiveRecord, so if a solution involves twiddling the source data before sending it to jbuilder, i'm not sure if any AR magic will apply. Still rather new to all this.
asked 34 secs ago
How do I "group" sets in Rails' jbuilder?
Aucun commentaire:
Enregistrer un commentaire