Reputation: 1250
I am trying to create a nested JSON that has data from various db tables and return it using format.json {render json: @Model}
For example a json structure like this:
{"Model1": [
{"id": 3, "name": "newURI", {"Model2": ["id": 4, "name":"vill"]}},
{"id": 1, "name": "bill", {"Model2": ["id": 1, "name":"lily"]}},
{"id": 2, "name": "ton", {"Model2": ["id": 2, "name":"bow"]}},
]}
I have searched around, but wasn't too successful. I saw Rabl, but the nested JSON generated is not well formed. Please help me if you can. Thanks
Upvotes: 0
Views: 1438
Reputation: 1050
A very simple approach to this would be to just :include related records with the objects that are returned in those controller requests. I use this in an API that lives in it's own namespaced route with a separate controller that only returns JSON and thereby keeps things clean and simple. Here's a simple example for a show action that returns contacts with their addresses as JSON:
/app/controllers/api/contacts_controller.rb
module Api
class ContactsController < ApplicationController
respond_to :json
...
def show
respond_with Contact.find(params[:id]), :include => :addresses
end
...
end
end
I assume that :include => related_model
would work in whatever controller setup you use as well. This will return a contact with a nested array of addresses that belong to this contact. Of course it works for index actions too.
Needless to say that you need to setup a relation in your models first, e.g. has_many :addresses in /models/contact.rb
Upvotes: 0
Reputation: 10701
A very new fancy way is using the representer pattern and the ROAR gem.
I've been using it for an API lately, and like it. These two posts describe it better than I will:
http://nicksda.apotomo.de/2011/12/ruby-on-rest-introducing-the-representer-pattern/
http://nicksda.apotomo.de/2011/12/ruby-on-rest-2-representers-and-the-dci-pattern/
You can define representer modules that allow for encoding or decoding json. Include them in your models, or extend them at runtime, and you have much control over json encoding logic.
These representers can include specific properties/methods, associated objects, and collections of associated objects, and allow you to specify how those nested elements are handled (i.e. what representer and class to use when encoding/decoding).
Here is the API I am working on with 3 layers of nesting for the Piece class (Piece -> AudioVersion -> AudioFile):
https://github.com/PRX/prx_client
Upvotes: 1