I was very happy to learn of as_json to make my code DRY. And I've added the following 开发者_Go百科to a model:
class ProductType < ActiveRecord::Base
has_many :component_types
def as_json(parameter)
{:name => self.name,
:description => self.description,
:children => self.componentTypes}
end
end
This is great. The only thing is that for my client side application, I need to wrap the response I get into this format, (where "items" contains what is created by as_json):
{
"identifier": "name",
"label": "name",
"items":
[
{
"name": "myName1",
"description": "myDesc1",
"children":[]
},
{
"name": "myName2",
"description": "myDesc2",
"children":[]
}
]
}
There are a lot of limitations to overriding as_json
, and your issue is one of them. I'd suggest having a look at the RABL gem as I think it will help you reach your goal.
精彩评论