将自定义属性附加到Rails上的JSON响应中的嵌套字段

时间:2017-02-22 19:37:44

标签: ruby-on-rails json

在我的应用程序中,我在Controller中有以下代码:

type AList []A
type BList []B
type CList []C

func (list *AList) GetIDs() []int64 { ... }
func (list *BList) GetIDs() []int64 { ... }
func (list *CList) GetIDs() []int64 { ... }

这让我回到了像这样的JSON:

def show
    @ratings = Rating.where(event_id: params[:id]).order(created_at: :desc)

    respond_to do |format|
      format.json { render json: @ratings.to_json(include: :app_user) }
    end
  end

如何将自定义属性添加到每个项目的 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"
    }
  },
  {
    "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

,自定义属性不同

1 个答案:

答案 0 :(得分: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"
      }
    }
  }