Rails API 版本控制,AMS 不使用自定义序列化程序



我正在开发一个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/与:

(for/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

OUTPUT for .../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'

任何帮助都会很感激。谢谢!

EDIT:命名空间有效!

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

唯一有效的解决方案是直接调用序列化器类:
  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

我终于得到了一个解决方案,使用each_serializer: V1::UserSerializercollectionsserializer: V2::UserSerializer的正常对象。

谢谢大家。

最新更新