Skip to content

Including a child association

fabrik42 edited this page Apr 20, 2011 · 2 revisions

Including a child association

You can easily include associations of your model in an api template:

class User < ActiveRecord::Base

  has_many :tasks

  acts_as_api

  api_accessible :user_with_tasks do |t| 
    t.add :tasks
  end

end

Control api template of included association

If the model Task has also an api template with the same name (in this case :user_with_tasks), this will automatically be taken for rendering!

In this example you would need:

class Task < ActiveRecord::Base

  belongs_to :user

  acts_as_api

  api_accessible :user_with_tasks do |t|
    t.add :title
    t.add :user_id
    t.add :description
    t.add :completed
  end

end

Setting another template for association

In case you want to pass another template for the association, you just have to pass an additional :template option.

class User < ActiveRecord::Base

  has_many :tasks

  acts_as_api

  api_accessible :user_with_tasks do |t| 
    t.add :tasks, :template => :public
  end

end

Which would render the following template for every single task of the user:

class Task < ActiveRecord::Base

  belongs_to :user

  acts_as_api

  api_accessible :public do |t| 
    t.add :title
    t.add :completed
  end

end