0

Total I have the following code:

def search
  @regions = Region.search(params[:searchPhrase]).page(params[:current].to_i).per_page(params[:rowCount].to_i)
  data = {
    current: @regions.current_page, 
    rowCount: @regions.per_page,
    total: @regions.count,
    rows: @regions
  }
  respond_with(data)
end

This gives me an output like:

{total: 20, current: 2, rowCount: 10, rows: [{id: 1, name: "Region"}, ...]}

This works fine, but I want the same format all over the application.

I've read some content about ActiveModel Seralizers gem, but I couldn't find a way of doing this the following:

  • Addind a root with a custom name. I know I cant set a root with AMS, but how can I name it?
  • Adding keys for a CollectionSerializer. I know I can use meta, but I don't want to keys to be under another key. I want the output as it is today.

Does anyone knows how to achieve this?

Wand Maker
  • 18,476
  • 8
  • 53
  • 87
lcguida
  • 3,787
  • 2
  • 33
  • 56

1 Answers1

0

You can create a RegionSerializer like this:

class RegionSerializer    
  attributes :current,
             :rowCount,
             :total,
             :regions

  def regions
    # get the regions here
  end
end

Then, in your controller, you can have something like this:

  def search

    render(
        root: :your_custom_root_name,
        json: rows,
        each_serializer: RegionSerializer
    )
  end

  private

  def rows
    # get collection_of_objects/rows here
  end

You can use the root option to specify the name of your root element and each_serializer option to specify the serializer to render your collection of objects as shown above.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • Yes, I can specify root in render (which I'm trying to avoid, so I don't have to do this in all controllers). But in your example, `rows` is not a property of `Region` but is the collection itself. – lcguida Sep 18 '15 at 16:23
  • I updated my answer. But, what do you really want to achieve? What did you mean by this line: `Addind a root with a custom name. I know I cant set a root with AMS, but how can I name it?` could you please elaborate this a bit? – K M Rakibul Islam Sep 19 '15 at 04:07