2017-02-22 24 views
1

在我的申请,我有以下我的控制器内的代码:并附上自定义属性与on Rails的JSON响应嵌套字段

​​

返回给我这样一个JSON:

[ 
    { 
    "id": 7, 
    "app_user_id": 2, 
    "event_id": 17, 
    "comentario": "Comment 1", 
    "nota": 10, 
    "created_at": "2017-02-22T13:50:40.000Z", 
    "updated_at": "2017-02-22T13:50:40.000Z", 
    "app_user": { 
     "id": 2, 
     "facebook_id": "1343401692386568", 
     "created_at": "2017-02-09T18:36:01.000Z", 
     "updated_at": "2017-02-09T18:36:01.000Z" 
    } 
    }, 
    { 
    "id": 6, 
    "app_user_id": 2, 
    "event_id": 17, 
    "comentario": "Comment 2", 
    "nota": 1, 
    "created_at": "2017-02-22T13:29:56.000Z", 
    "updated_at": "2017-02-22T13:29:56.000Z", 
    "app_user": { 
     "id": 2, 
     "facebook_id": "1343401692386568", 
     "created_at": "2017-02-09T18:36:01.000Z", 
     "updated_at": "2017-02-09T18:36:01.000Z" 
    } 
    }, 
] 

如何将自定义属性添加到每个项目的app_user部分?例如:

[ 
    { 
    "id": 7, 
    "app_user_id": 2, 
    "event_id": 17, 
    "comentario": "Comment 1", 
    "nota": 10, 
    "created_at": "2017-02-22T13:50:40.000Z", 
    "updated_at": "2017-02-22T13:50:40.000Z", 
    "app_user": { 
     "id": 2, 
     "facebook_id": "1343401692386568", 
     "created_at": "2017-02-09T18:36:01.000Z", 
     "updated_at": "2017-02-09T18:36:01.000Z", 
     "custom_attr1": "value1", 
     "custom_attr2": "value2", 
    } 
    }, 
    { 
    "id": 6, 
    "app_user_id": 2, 
    "event_id": 17, 
    "comentario": "Comment 2", 
    "nota": 1, 
    "created_at": "2017-02-22T13:29:56.000Z", 
    "updated_at": "2017-02-22T13:29:56.000Z", 
    "app_user": { 
     "id": 2, 
     "facebook_id": "1343401692386568", 
     "created_at": "2017-02-09T18:36:01.000Z", 
     "updated_at": "2017-02-09T18:36:01.000Z", 
     "custom_attr1": "value1", 
     "custom_attr2": "value2", 
    } 
    }, 
] 

的自定义属性将根据每个APP_USER ID不同

回答

0

如果你不依赖于扁平结构,你可以做到以下几点:

class AppUser < ActiveRecord::Base 
    # ... 

    def custom_attributes 
    # custom attributes different for each app_user 
    # return anything you want 
    { attr1: "value1", attr2: "value2" } 
    end 
end 

# controller 
format.json { render json: @ratings.to_json(include: { app_user: { methods: :custom_attributes}}) } 

这将给出下一个输出:

{ 
    "id": 6, 
    "app_user_id": 2, 
    "event_id": 17, 
    "comentario": "Comment 2", 
    "nota": 1, 
    "created_at": "2017-02-22T13:29:56.000Z", 
    "updated_at": "2017-02-22T13:29:56.000Z", 
    "app_user": { 
     "id": 2, 
     "facebook_id": "1343401692386568", 
     "created_at": "2017-02-09T18:36:01.000Z", 
     "updated_at": "2017-02-09T18:36:01.000Z", 
     "custom_attributes": { 
     "attr1": "value1", 
     "attr2": "value2" 
     } 
    } 
    } 
+0

我可以在** custom_attributes **函数中返回多个值,所以结果JSON应该是'“custom_attributes”:{attr1:value1,attr2:value2}'? –

+0

@AlexandreSottanideCarvalho是的,如果你从'custom_attributes'方法返回散列 –

+0

谢谢,那正是我一直在寻找的东西 –