【问题标题】:Rails API versioning, AMS doesn't use custom serializersRails API 版本控制,AMS 不使用自定义序列化程序
【发布时间】:2016-09-17 17:07:39
【问题描述】:

我正在开发一个 Rails 应用程序,并且正在对 API 进行版本控制。

关注RailsCast #350 我有这个:

routes.rb

namespace :v1 do         
  #resources for version 1
end

namespace :v2 do
  #resources for version 2
end

我使用active_model_serializer,我有app/serializers/v1/.../v2/ 与:

(对于 /v1)

module V1
  class ResourceSerializer < ActiveModel::Serializer
      attributes :id
  end
end

(对于 /v2)

module V2
  class ResourceSerializer < ActiveModel::Serializer
      attributes :id, :data
  end
end

但 Rails 不调用我的自定义序列化程序。

module V1

  class ResourcesController < ApplicationController

    def show
      @resource = Resource.find(params[:id])
      render json: @resource
    end
  end
end

输出.../v1/resources/1

{"id":1,"name":"...","city":"...","created_at":"...","updated_at":"2..."}

而不是 {"id":1}

如果我放 render json: @resources, serializer: ResourceSerializer 它会检索 undefined method 'read_attribute_for_serialization'

任何帮助将不胜感激。谢谢!

编辑:命名空间有效!

【问题讨论】:

    标签: ruby-on-rails json rest api ruby-on-rails-5


    【解决方案1】:

    我也遇到了这个问题,我尝试了很多解决方案,但都不适合我

    唯一可行的解​​决方案是直接调用序列化程序类:

      render json: V1::ResourceSerializer.new(@resource)
    

    如果您的问题只是“未定义的方法'read_attribute_for_serialization'”,请将ActiveModel::Serialization 包含到您的ActiveModel 子类中

      module V1
        class ResourceSerializer < ActiveModel::Serializer
          include ActiveModel::Serialization
    
          attributes :id
        end
      end
    

    【讨论】:

      【解决方案2】:

      我终于找到了一个解决方案,将each_serializer: V1::UserSerializer 用于collectionsserializer: V2::UserSerializer 用于普通对象。

      谢谢大家。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-19
        • 1970-01-01
        • 2011-03-12
        • 2016-10-31
        • 2018-11-19
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        相关资源
        最近更新 更多