【问题标题】:active_model_serializers not working in rails-apiactive_model_serializers 在 rails-api 中不起作用
【发布时间】:2014-11-29 07:26:09
【问题描述】:

我找了很多遍,没有找到解决办法。

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

我明白了:

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

我想要:

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

【问题讨论】:

    标签: ruby-on-rails-4 active-model-serializers rails-api


    【解决方案1】:

    看起来您正在尝试禁用 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
    

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

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

    有关更多信息,这里是最新版本自述文件页面相关部分的链接。

    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
    

    【讨论】:

    • 这似乎不是我唯一的问题,接受根元素问题,我的序列化程序根本没有被调用,就像它不存在一样。我一直在网上搜索,发现人们做的事情很少,但没有人帮助过我。
    • Zamith 的下一个答案解决了序列化程序未与渲染步骤挂钩的问题,可能值得编辑此答案以包含它。
    • 只需添加 include ActionController::Serialization 就可以了(仅限 Rails 5 API)。
    【解决方案2】:

    我在使用最新的 rails-api 4.2.0beta 时遇到了同样的问题

    序列化器没有被拾取。我将 rails-api 降级到 4.1.5 并且它有效。 不要忘记删除

    config.active_record.raise_in_transactional_callbacks = true
    

    从 config/application.rb 会在 4.2.0 之前的版本中引发错误

    【讨论】:

    【解决方案3】:

    这是因为rails-api中默认不加载序列化。你必须这样做:

    class ApplicationController < ActionController::API
      include ::ActionController::Serialization
    end
    

    【讨论】:

    • 是的,这就是问题所在。
    • 没错,如果你的ApplicationController继承自ActionController::API,那么你应该手动包含序列化
    【解决方案4】:

    如果你用的是最新版本,好像不能再按这个设置默认适配器了:

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

    解决方法是使用

        render json: object_to_render, adapter: :json
    

    另外,没有必要再添加这个了:

        include ::ActionController::Serialization
    

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

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2020-04-15
      • 2017-03-19
      • 1970-01-01
      • 2014-07-05
      相关资源
      最近更新 更多