使用jbuilder在具有自定义顺序的JSON结构中插入自定义键:值对



在控制器的显示方法中,我使用查询设置了@object

@object = WorkOrder.find(params[:id])  

现在,show.json.jbuilder模板的代码为:

json.extract! @object, :id, :note, :status, :created_at
json.store_name @object.store.display_name

o/p是

{
  "id": 31,
  "note": "work_order for store A",
  "status": "complete",
  "created_at": "2015-11-26T11:16:53.000Z",
  "store_name": "store name"
}

现在,如何在"status"one_answers"created_at"之间插入"store_name"自定义密钥?

如果您想要按特定顺序添加属性,那么自己添加可能会更好。

Jbuilder文件:

json.id @object.id
json.note @object.note
json.status @object.status
json.display_name @object.store.display_name
json.created_at @object.created_at

输出

{
  "id": 31,
  "note": "work_order for store A",
  "status": "complete",
  "display_name": "store name",
  "created_at": "2015-11-26T11:16:53.000Z"
}

我建议你嵌入关系。如果您想添加Store的其他属性,它的可伸缩性更好。

示例:

Jbuilder文件:

json.id @object.id
json.note @object.note
json.status @object.status
json.store do
  json.name @object.store.display_name
end
json.created_at @object.created_at

输出

{
  "id": 31,
  "note": "work_order for store A",
  "status": "complete",
  "store": {
    "name": "store name"
  },
  "created_at": "2015-11-26T11:16:53.000Z"
}

稍后,您可以在不破坏接口的情况下轻松地向Store哈希添加属性。

您还可以让Rails发挥这样的魔力:

render :json => @object, :include => {:store => {:only => :display_name}}

恐怕它没有办法把store_name带到其他位置。你应该对你所拥有的一切感到高兴。

最新更新