Ruby on rails 4 活动\u模型\u序列化程序在rails api中不工作

Ruby on rails 4 活动\u模型\u序列化程序在rails api中不工作,ruby-on-rails-4,active-model-serializers,rails-api,Ruby On Rails 4,Active Model Serializers,Rails Api,我一直在四处寻找,没有找到解决办法 我有一个rails API应用程序 以及简单的模型、控制器和序列化程序 但是,当我尝试获取索引路由时,我得到的是标准rails JSON未序列化 class Tag < ActiveRecord::Base end class TagSerializer < ActiveModel::Serializer attributes :id, :title end class TagsController < ApplicationCont

我一直在四处寻找,没有找到解决办法

我有一个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
我想:

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

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

如何实现这一点可能取决于您使用的是哪个版本的
active\u model\u序列化程序

0.9.x
中,您可以在Rails初始值设定项中执行以下操作:

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

# Disable for ArraySerializer
ActiveModel::ArraySerializer.root = false
或者简单地说,在控制器操作中:

class TagsController < ApplicationController
  def index
    render json: Tag.all, root: false
  end
end
class标记控制器
有关更多信息,请参阅最新版本自述页面相关部分的链接

--

注意,还请确保您实际包含了处理序列化的代码,因为默认情况下ActionController::API不包含这些代码。比如说,

class ApplicationController < ActionController::API
  include ActionController::Serialization
end
class ApplicationController
在使用最新的rails api 4.2.0beta版时,我也遇到了同样的问题

序列化程序没有被捕获。我将RailsAPI降级到4.1.5,它成功了。 别忘了取下

config.active_record.raise_in_transactional_callbacks = true

在config/application.rb中,它将在4.2.0之前的版本中引发一个错误,这是因为rails api中默认不加载序列化。你必须这样做:

class ApplicationController < ActionController::API
  include ::ActionController::Serialization
end
class ApplicationController
如果您使用的是最新版本,似乎无法再根据以下内容设置默认适配器:

解决方法是使用

    render json: object_to_render, adapter: :json
此外,无需再添加以下内容:

    include ::ActionController::Serialization

看到Rails api在没有详细文档的情况下不断地在版本之间更改,我感到很沮丧

这似乎不是我唯一的问题,接受根元素问题,我的序列化程序根本没有被调用,就像它不存在一样。我一直在网上搜索,我发现很少有人做过但没有人帮过我。Zamith的下一个答案解决了序列化程序没有连接到渲染步骤的问题,可能值得编辑这个答案来包含它。只需添加
include ActionController::Serialization
就可以了(仅限Rails 5 API)。这在0.9.3中已修复。您可以在此处阅读Github线程:是的,这就是问题所在。确切地说,如果您的ApplicationController继承自ActionController::API,那么您应该手动包含序列化
    include ::ActionController::Serialization