I have a Rails server returning data to my mobile App as JSON, as follows,
In controller,
format.json { render :json => @game }
Which returns,
{"game":{"created_at":"Thu, 14 Apr 2011 11:14","title":"Banana throwing","updated_at":"Thu, 14 Apr 2011 11:16","id":5,"day":"2011-07-14","location_id":5}}
The returned record includes a reference from the 'game' table to another table, 'location', and specifically the entry with the id of 5 in that table.
Now, my mobile App could jump through some hoops to resolve that location_id in the other table, but it would be a whole lot more straight-forward if the JSON that is initially returned had already resolve开发者_开发知识库d the location_id value and included the expanded 'location' record in the original result, something like,
{"game":{"created_at":"Thu, 14 Apr 2011 11:14","title":"Banana throwing","updated_at":"Thu, 14 Apr 2011 11:16","id":5,"day":"2011-07-14","location":{"place":"Buckingham Palace"}}}
...where entry with id of 5 in the location table has been expanded as nested JSON.
Is it possible to do this on the server side, and if so how?
Any help with this would be very much appreciated.
Thank you.
Try:
format.json { render :json => @person.to_json(:include => [:location]) }
Sorry for the terse response, but to_json
with :include
is pretty much it. I have not tested it in the controller just now but gave it a go at the console and it was OK.
精彩评论