Active_model_serializers not working in rails-api
I searched a lot and didn't find a solution.
I have a rails-api app and a simple model, controller and serializer
but when i try to get the index route i get standard json rails 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 to:
[
{ id: 1, title: 'kifla'},
{ .....
source to share
It looks like you are trying to disable the root element of your json output.
How this is achieved may depend on which version active_model_serializers
you are using.
As 0.9.x
you can do something like this in 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 information, see the links to the relevant sections in the latest README pages.
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
-
Please note, make sure you are actually including the code that handles serialization, as ActionController :: API is not used by default. For example,
class ApplicationController < ActionController::API
include ActionController::Serialization
end
source to share
I had the same problem using the most recent rails-api 4.2.0beta p>
Serializers didn't pick up. I downgraded rails-api to 4.1.5 and it worked. Remember to delete
config.active_record.raise_in_transactional_callbacks = true
from config / application.rb this will throw an error in versions before 4.2.0
source to share
If you are using the latest version, it seems that you cannot set the default adapter anymore according to this:
https://github.com/rails-api/active_model_serializers/issues/1683
The workaround is to use
render json: object_to_render, adapter: :json
Also, there is no need to add this anymore:
include ::ActionController::Serialization
It's frustrating how the Rails api keeps changing version to version without detailed documentation.
source to share