【问题标题】:How to structure JSON code in Ruby如何在 Ruby 中构建 JSON 代码
【发布时间】:2012-07-30 19:43:55
【问题描述】:

我有一个新手问题。

下面的 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"
        }
    }
]

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 json


    【解决方案1】:

    如果您希望所有模型都具有这种行为,您可以这样做

    ActiveRecord::Base.include_root_in_json = true
    

    在初始化器中。

    对于单个模型,使用

    self.include_root_in_json = true
    

    在模型本身中。

    【讨论】:

      【解决方案2】:

      从 Rails 3.2 开始,您可以:

      format.json {render json: @customers.to_json(:root => true)}
      

      【讨论】:

        【解决方案3】:

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

        format.json {render json: @customers.map{ |x| {'customer' => x } }.to_json}
        

        【讨论】:

        • 如果您的 API 可以为一个请求发回多种类型的数据(在多路复用调用以减少移动设备调制解调器上的闲聊非常有用),则此格式使用其数据类型标记每个数据包。换句话说,将对象类型与对象数据一起发送可以让您的客户端在解析时更加智能。
        猜你喜欢
        • 2015-02-25
        • 2016-07-25
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多