找到你要的答案

Q:Rails REST api setup: json arrays for multiple value columns

Q:Rails的REST API设置:JSON数组的多值的列

I'm a little confused, and need some design help/input

I have a relational DB, and what I am doing is creating views/materialized views from my data that RoR will use activerecord to consume and output in json or xml, but I'm mainly concerned with JSON in this question

lets say i create a view from customer and phone tables

after creating that view, a select outputs the following rows

+-----+----+----------+----------+--------------+
|     | ID |   name   | Phone_id | Phone_number |
+-----+----+----------+----------+--------------+
|   1 | 77 | Jay Blow |      771 |   1234567889 |
|   2 | 77 | Jay Blow |      772 |   5674291988 |
+-----+----+----------+----------+--------------+

i place the new view in the activerecord, and i want the JSON to be represneted like this after calling the route /customer/77

{
    "id": "77",
    "name": "Jay Blow",
    "phone": [
        {
            "id": "771",
            "number": "1234567889"
        },
        {
            "id": "772",
            "number": "5674291988"
        }
    ]
}

am i off base here to want this to be the desired way to output the data? Or am i not considering something vital? like this isnt the way active record works?

我有点困惑,需要一些设计帮助/输入

我有一个关系数据库,和我所做的就是创建视图/视图从我的数据,误差将使用ActiveRecord消耗和JSON或XML输出,但是我主要关心这一问题的JSON

让我创建一个视图从客户和电话表

创建该视图后,选择输出下列行

+-----+----+----------+----------+--------------+
|     | ID |   name   | Phone_id | Phone_number |
+-----+----+----------+----------+--------------+
|   1 | 77 | Jay Blow |      771 |   1234567889 |
|   2 | 77 | Jay Blow |      772 |   5674291988 |
+-----+----+----------+----------+--------------+

我把新的观点在他,我想是这样的represneted JSON调用路径/客户/ 77

{
    "id": "77",
    "name": "Jay Blow",
    "phone": [
        {
            "id": "771",
            "number": "1234567889"
        },
        {
            "id": "772",
            "number": "5674291988"
        }
    ]
}

我在这里的基地,希望这是理想的方式来输出数据?或者我没有考虑重要的事情?像这样的活动记录是不是工作的方式?

answer1: 回答1:

You can create response like {:id => 123, :name => 'name here', :phone => {:id => 23, :number => '' }}

您可以创建响应像{:ID = & gt;123:名称= & gt;的名字”:手机= & gt;{:ID = & gt;23:数量= & gt;”} }

answer2: 回答2:

You want to write a custom renderer for your json. I suggest you to check JBuilder, it's simple and effective: you write a file in app/views/yourcontroller/index.jbuilder and with some simple Ruby code you are able to generate whatever JSON output you want. In this specific case however, if your Customer has_many phones, you can do the following:

customer = Customer.find(customerid)
render json: customer.as_json(include: [:phones])

你想写一个JSON自定义渲染器。我建议你去看看JBuilder,这是简单而有效的:你写的应用程序/观点/ yourcontroller / index.jbuilder和一些简单的Ruby代码可以生成任何JSON输出你想要的文件。然而在这种特定的情况下,如果你的客户has_many手机,你可以做以下:

customer = Customer.find(customerid)
render json: customer.as_json(include: [:phones])
ruby-on-rails  json  activerecord