I have two rails models:
A Milestone has many Tasks A Task belongs to a Milestone
In my controller I call the following:
@milestones = Milestone.all
render :json => @milestones.to_json(:include => :tasks)
Which gives me:
[ {
"id": 5,
"name": "This is milestone #1",
"tasks": [{
"complete": false,
"id": 60,
"name": "aaaaa",
"milestone_id": 5,
}, {
"complete": false,
"id": 62,
"name": "ccccc",
"milestone_id": 5,
}
]
}, {
"id": 6,
"name": "This is milestone #2",
"tasks": [{
"complete": false,
"id": 65,
"name": "ffffff",
"milestone_id": 5,
}, {
"complete": false,
"id": 66,
"name": "gggggg",
"milestone_id": 5,
}
]
}
]
But I need to be able to easily navigate through the JSON, so I'd like to be able to format it like this (notice each "sub array" is labeled with "milestone_ID" or "task_ID"):
[
"milestone_5": {
"id": 5,
"name": "This is milestone #1",
"tasks": [
"task_60":{
"complete": false,
"id": 60,
"name": "aaaaa",
"milestone_id": 5,
},
"task_62":{
"complete": false,
"id": 62,
"name": "ccccc",
"milestone_id": 5,
}
]
},
"milestone_6":{
"id": 6,
"name": "This is milestone #2",
"tasks": [
"task_65":{
"complete": false,
"id": 65,
"name": "ffffff",
"milestone_id": 5,
},
"task_66":{
"complete": false,
"id": 66,
"name": "gggggg",
"milestone_id": 5,
}
]
}
]
Does anybody have any idea how to get Rails to custom format JSON. Even if I have to lose the "milestone_" part and just spit out the ID, that would be very helpful.
Thanks!