1

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!

4

1 回答 1

3

看看json_builder gem。

您所要求的当然是可行的,但就个人而言,当您开始使用控制器的 json 输出做任何远程有用的事情时,默认to_json方法变得笨拙。最好明确输出您希望 json 的样子。

特别是在您的 json_builder 文件中...

milestone.json.json_builder

@milestones.each do |milestone|
  key "milestone_#{milestone.id}" do
    id milestone.id
    name milestone.name
  end
end

等等等等。我相信这会成功。

编辑:我倾向于只包含模型中我需要的任何资源消耗我的 json 的确切字段。这将提高性能,并且可以在出现问题时使调试变得更容易。哪些字段将出现在哪里也很明显。

于 2013-05-03T21:18:09.297 回答