3

我有一个新手问题。

下面的 Ruby 代码返回输出 1 中显示的 JSON。如何修改它以返回 Output2 中显示的 JSON,即每条记录都在客户记录中。

代码:

def index
    @customers = Customer.all
    respond_to do |format|
        format.html
        format.json {render json: @customers.to_json}
    end
end

输出1:

[
    {
        "address":"123 Main Ave, Palo Alto, CA",
        "created_at":"2012-07-10T19:49:24Z",
        "id":1,
        "name":"ACME Software Inc.",
        "phone":"1-650-555-1500",
        "updated_at":"2012-07-10T19:49:24Z"
    },
    {
        "address":"555 Art Drive, Mountain View, CA",
        "created_at":"2012-07-10T19:50:19Z",
        "id":2,
        "name":"My Company",
        "phone":"1-415-555-1000",
        "updated_at":"2012-07-10T19:50:19Z"
    }
]

输出2:

[
    {
        "customer":{
            "address":"123 Main Ave, Palo Alto, CA",
            "created_at":"2012-07-10T19:49:24Z",
            "id":1,
            "name":"ACME Software Inc.",
            "phone":"1-650-555-1500",
            "updated_at":"2012-07-10T19:49:24Z"
        }
    },
    {
        "customer":{
            "address":"555 Art Drive, Mountain View, CA",
            "created_at":"2012-07-10T19:50:19Z",
            "id":2,
            "name":"My Company",
            "phone":"1-415-555-1000",
            "updated_at":"2012-07-10T19:50:19Z"
        }
    }
]
4

3 回答 3

4

如果您希望所有模型都具有此行为,则可以执行

ActiveRecord::Base.include_root_in_json = true

在初始化程序中。

对于单个模型,使用

self.include_root_in_json = true

在模型本身。

于 2012-07-30T19:48:51.340 回答
3

从 Rails 3.2 开始,您可以:

format.json {render json: @customers.to_json(:root => true)}
于 2012-07-30T19:51:39.797 回答
0

好吧,我不知道你为什么想要这个,但这是一种简单的方法:

format.json {render json: @customers.map{ |x| {'customer' => x } }.to_json}
于 2012-07-30T19:46:34.730 回答