active_model_serializers not working in rails-api

Azaryan picture Azaryan · Oct 4, 2014 · Viewed 10.5k times · Source

I have been looking around a lot and have not found a solution.

I have a rails-API application and simple model, controller, and serializer

but when I try to get index route I get standard rails JSON not serialized.

class Tag < ActiveRecord::Base
end

class TagSerializer < ActiveModel::Serializer
  attributes :id, :title
end

class TagsController < ApplicationController
  def index
    render json: Tag.all
  end
end

I get:

[
  tag: {
    id: 1,
    title: 'kifla'
  },
  tag: 
 .....

I want:

[
  { id: 1, title: 'kifla'},
  { .....

Answer

Zamith picture Zamith · Dec 19, 2014

That's because the serialization is not loaded by default in rails-api. You have to do this:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
end