Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

active_model_serializers not working in rails-api

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'},
  { .....
like image 673
Azaryan Avatar asked Oct 04 '14 11:10

Azaryan


2 Answers

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
like image 190
Zamith Avatar answered Sep 20 '22 18:09

Zamith


Looks like you're trying to disable the root element of your json output.

How this is achieved may depend on which version of active_model_serializers you're using.

In 0.9.x, you could do something like this in a Rails initializer:

# Disable for all serializers (except ArraySerializer)
ActiveModel::Serializer.root = false

# Disable for ArraySerializer
ActiveModel::ArraySerializer.root = false

Or simply, in your controller action:

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

For more info, here are links to relevant sections of the README pages of recent versions.

https://github.com/rails-api/active_model_serializers/tree/0-9-stable#disabling-the-root-element

https://github.com/rails-api/active_model_serializers/tree/0-8-stable#disabling-the-root-element

--

Note, please make sure also that you're actually including the code that handles serialization, as ActionController::API does not by default. For example,

class ApplicationController < ActionController::API
  include ActionController::Serialization
end
like image 40
rossta Avatar answered Sep 21 '22 18:09

rossta