简体   繁体   English

版本控制ActiveModel :: Serializer

[英]Versioning ActiveModel::Serializer

I'm using the gem active_model_serializers and I'm facing some issues with versioning. 我正在使用gem active_model_serializers,并且遇到版本控制方面的问题。

Controllers 控制器

In app/controllers/v1/contracts_controller.rb app/controllers/v1/contracts_controller.rb

module V1
    class ContractsController < ApiController

        def index
            @contracts = Contract.all
            render json: @contracts
        end

    end
end

In app/controllers/v2/contracts_controller.rb app/controllers/v2/contracts_controller.rb

module V2
    class ContractsController < ApiController

        def index
            @contracts = Contract.all
            render json: @contracts
        end

    end
end

Serializers 串行器

In app/serializers/v1/contract_serializer.rb app/serializers/v1/contract_serializer.rb

class ContractSerializer < ActiveModel::Serializer
    attributes :id
end

In app/serializers/v2/contract_serializer.rb app/serializers/v2/contract_serializer.rb

class ContractSerializer < ActiveModel::Serializer
    attributes :id, :name
end

Whether I call the route /v1/contracts or /v2/contracts , the rendered json include the contract name, which means that the serializer in v2 seems to be always called. 无论我将路由称为/v1/contracts还是/v2/contracts ,呈现的json都包含合同名称,这意味着v2中的序列化程序似乎总是被调用。

FYI, I added config.autoload_paths += Dir[Rails.root.join('app', 'serializers', '**/')] in config/application.rb 仅供参考,我在config/application.rb添加了config.autoload_paths += Dir[Rails.root.join('app', 'serializers', '**/')]

You need to specify the serializers in your controllers, eg my answer here 您需要在控制器中指定序列化器,例如我的答案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM