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

Inserting custom key:value pair in JSON structure with custom order using jbuilder

在控制器的显示方法中,我使用查询设置了@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' 和 'created_at' 之间插入 'store_name' 自定义密钥?

恐怕没办法把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}}