active_model_serializers不在rails-api中工作

Aza*_*yan 5 rails-api active-model-serializers ruby-on-rails-4

我一直在四处寻找并找不到解决方案.

我有rails-api应用程序和简单的模型,控制器和序列化器

但是当我尝试获得索引路由时,我得到的标准rails json没有被序列化.

class Tag < ActiveRecord::Base
end

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

class TagsController < ApplicationController
  def index
    render json: Tag.all
  end
end
Run Code Online (Sandbox Code Playgroud)

我明白了:

[
  tag: {
    id: 1,
    title: 'kifla'
  },
  tag: 
 .....
Run Code Online (Sandbox Code Playgroud)

我想要:

[
  { id: 1, title: 'kifla'},
  { .....
Run Code Online (Sandbox Code Playgroud)

Zam*_*ith 32

那是因为在rails-api中默认没有加载序列化.你必须这样做:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
end
Run Code Online (Sandbox Code Playgroud)


ros*_*sta 20

看起来你正在尝试禁用 json输出的根元素.

如何实现这可能取决于active_model_serializers您使用的是哪个版本.

0.9.x,您可以在Rails初始化程序中执行以下操作:

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

# Disable for ArraySerializer
ActiveModel::ArraySerializer.root = false
Run Code Online (Sandbox Code Playgroud)

或简单地说,在您的控制器操作中:

class TagsController < ApplicationController
  def index
    render json: Tag.all, root: false
  end
end
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅最新版本的README页面相关部分的链接.

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

-

请注意,请确保您实际上包含了处理序列化的代码,因为ActionController :: API默认情况下不会.例如,

class ApplicationController < ActionController::API
  include ActionController::Serialization
end
Run Code Online (Sandbox Code Playgroud)


OMG*_*POP 5

如果您使用的是最新版本,则似乎无法根据此设置默认适配器:

https://github.com/rails-api/active_model_serializers/issues/1683

解决方法是使用

    render json: object_to_render, adapter: :json
Run Code Online (Sandbox Code Playgroud)

另外,也不再需要添加以下内容:

    include ::ActionController::Serialization
Run Code Online (Sandbox Code Playgroud)

沮丧地看到Rails api如何在没有详细文档的情况下不断地更改版本。