开发者

Rails 3: Wrapping as_json response with additional lines

开发者 https://www.devze.com 2023-03-19 15:48 出处:网络
I was very happy to learn of as_json to make my code DRY. And I\'ve added the following 开发者_Go百科to a model:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消