fabrik42/acts_as_api

Render two arrays of objects from same model in groups

Opened this issue · 2 comments

Hello

I already searched trough the wiki but i didn't find a solution.

I have two arrays / ActiveRecord relations which contain objects from the same model which has
api_accessible :name do |t|
t.add :id
t.add :first_name
t.add :last_name
end

The arrays represent two groups of different users
and i want to render them in one JSON object which contains both of the arrays like
-{

  • group_1 : [
    {..},
    users of group_1 rendered over acts_as_api
    ],
    • group_2 : [
      {..},
      users of group_2 rendered over acts_as_api
      ]
      }

Can i realize this using acts_as_api?
Thanks for your help!

You are right, this is currently not documented. An approach could be to create a simple class that provides the grouping:

class GroupedUsers
  extend ActsAsApi::Base

  attr_accessor :group_one, :group_two

  def initialize(group_one, group_two)
    @group_one = group_one
    @group_two = group_two
  end

  def model_name
    'users'
  end

  acts_as_api

  api_accessible :name do |t|
    t.add :group_one
    t.add :group_two
  end
end

Then you can do something like this in your controller:

grouped = GroupedUsers.new(@users_one, @users_two)

respond_to do |format|
  format.json  { render_for_api :name_only, :json => grouped, :root => :users  }
end

Which should result in this json response:

{
    users: {
        group_one: [
            {
                first_name: "Luke"
            },
            {
                first_name: "Leia"
            }
        ],
        group_two: [
            {
                first_name: "Chewbacca"
            },
            {
                first_name: "Han"
            }
        ]
    }
}

I hope this helps. :)
Let me know if you come up with a better solution.

Hello... just implemented it like you suggested and it works great. I had no idea how to implement it without a lot of ugly code. Thanks!