Paul
Paul

Reputation: 21

Rails 3: Wrapping as_json response with additional lines

I was very happy to learn of as_json to make my code DRY. And I've added the following 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":[]
      }
    ]
}

Upvotes: 1

Views: 465

Answers (1)

Brian Driscoll
Brian Driscoll

Reputation: 19635

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.

Upvotes: 2

Related Questions