Skip to content

Creating a completely different response structure

fabrik42 edited this page Apr 20, 2011 · 3 revisions

Creating a completely different response structure

In case you want to create a deeper response structure that is completely unrelated to the structure of the model and its associations: The easiest way is to pass a method that will return a hash.

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :nested_sub_hash do |t| 
    t.add :sub_hash
  end

  def sub_hash
    {
      :foo => "bar",
      :hello => "world"
    }
  end

end

Creates a response like:

{
  "user": {
    "sub_hash": {
      "foo": "bar",
      "hello": "world"
    }
  }
}

Going all nuts

no comment here...

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :nested_sub_node do |t| 
    t.add Hash[:foo, Hash[:bar, :last_name]], :as => :sub_nodes
  end

end

Would return something like this:

{
  "user": {
    "sub_nodes": {
      "foo": {
        "bar": "Skywalker"
      }
    }
  }
}