2

In show method for a controller i have @object setup with query

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

Now, the show.json.jbuilder template has code as:

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

and the o/p is,

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

Now, how to insert 'store_name' custom key in between 'status' and 'created_at' ?

Tobias
  • 4,523
  • 2
  • 20
  • 40
codemilan
  • 1,072
  • 3
  • 12
  • 32

3 Answers3

3

If you want the attributes in a specific order than it would be probably better if you add them by yourself.

Jbuilder file:

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

Output

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

I would recommend you to embed relations. It's better scaleable if you want to add other attributes of the Store.

Example:

Jbuilder file:

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

Output

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

Later you can easily add attributes to the Store hash without breaking the interface.

Tobias
  • 4,523
  • 2
  • 20
  • 40
1

You can also let Rails do the magic like this:

render :json => @object, :include => {:store => {:only => :display_name}}
bo-oz
  • 2,842
  • 2
  • 24
  • 44
-2

I'm afraid it has no way to bring store_name come to other position. YOu should happy with things that you have.

huyhoang-vn
  • 335
  • 1
  • 3
  • 13