Reputation: 20538
I am building a Rails/Backbone app and I will show users in a table. I want to create a JSON tree which is grouped on the user ID/Name.
This is how it looks now
[{
"total_entries": 2
},
{
"entries": [{
"id": 21,
"status": "pending",
"starts_at_date": "2018-02-02",
"starts_at_time": "12:00",
"ends_at_date": "2018-02-02",
"ends_at_time": "12:00",
"description": "",
"ttype": "vacation",
"sum": 0,
"user": {
"id": 1,
"fullname": "Marcus Lurem"
},
"timetype": null,
"pause": 0,
"can_manage": true
},
{
"id": 22,
"status": "pending",
"starts_at_date": "2018-02-07",
"starts_at_time": "12:00",
"ends_at_date": "2018-02-07",
"ends_at_time": "12:00",
"description": "",
"ttype": "doctor",
"sum": 0,
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"timetype": null,
"pause": 0,
"can_manage": true
}
]
}
]
I need it to be grouped on the name.
This is how I build the JSON object now.
json.array! [0,1] do |index|
if index == 0
json.total_entries @total
else
json.entries @events do |event|
json.extract! event, :id, :starts_at_date, :starts_at_time, :ends_at_date, :ends_at_time, :description, :ttype
json.sum event.sum
json.user event.user, :id, :fullname
json.can_manage true
end
end
end
Update
Should look like this more or less.
Upvotes: 0
Views: 292
Reputation: 484
You can use something like this:
json.entries @events.group_by(&:user) do |user, events|
json.user :id, :fullname
json.events events do |event|
json.extract! event, :id, :starts_at_date, :starts_at_time, :ends_at_date, :ends_at_time, :description, :ttype
end
end
Upvotes: 1