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'},
{ .....
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