我很高兴得知as_json让我的代码DRY。我已将以下内容添加到模型中:
class ProductType < ActiveRecord::Base
has_many :component_types
def as_json(parameter)
{:name => self.name,
:description => self.description,
:children => self.componentTypes}
end
end
这很棒。唯一的问题是,对于我的客户端应用程序,我需要将响应包装到这种格式中,(其中“items”包含as_json创建的内容):
{
"identifier": "name",
"label": "name",
"items":
[
{
"name": "myName1",
"description": "myDesc1",
"children":[]
},
{
"name": "myName2",
"description": "myDesc2",
"children":[]
}
]
}