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
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