I have a newbie question.
The Ruby code below returns JSON shown in Output1. How do I modify this to return the JSON shown in Output2 i.e., each record is within customer record.
def index
@customers = Customer.all
respond_to do |format|
format.html
format.json {render json: @customers.to_json}
end
end
[
{
"address":"123 Main Ave, Palo Alto, CA",
"created_at":"2012-07-10T19:49:24Z",
"id":1,
"name":"ACME Software Inc.",
"phone":"1-650-555-1500",
"updated_at":"2012-07-10T19:49:24Z"
},
{
"address":"555 Art Drive, Mountain View, CA",
"created_at":"2012-07-10T19:50:19Z",
"id":2,
"name":"My Company",
"phone":"1-415-555-1000",
"updated_at":"2012-07-10T19:50:19Z"
}
]
[
{
"customer":{
"address":"123 Main Ave, Palo Alto, CA",
"created_at":"2012-07-10T19:49:24Z",
"id":1,
"name":"ACME Software Inc.",
"phone":"1-650-555-1500",
"updated_at":"2012-07-10T19:49:24Z"
}
},
{
"customer":{
"address":"555 Art Drive, Mountain View, CA",
"created_at":"2012-07-10T19:50:19Z",
"id":2,
"name":"My Company",
"phone":"1-415-555-1000",
"updated_at":"2012-07-10T19:50:19Z"
}
}
]
If you want this behavior for all models, you can do
ActiveRecord::Base.include_root_in_json = true
in an initializer.
For a single model, use
self.include_root_in_json = true
in the model itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With