2016-06-28 81 views
1

我有版本系統的api。主動模型序列化不能與api版本兼容

我控制器

module Api;module V1 
     class PlansController < ApplicationController   
      def show 
      @plan = Plan.find(params[:id]) 
      render json: @plan 
      end 
     end 
    end;end 

我有文件夾串行器/ API/V1在那裏我有自動plan_serializer.rb

module Api;module V1 
    class PlanSerializer < ActiveModel::Serializer 
     attributes :name, :amount, :days 
    end 
end;end 

但它不是序列化JSON響應。 請告訴我我在做什麼錯?

我也嘗試添加

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

但還是它不工作。

如果我做

render json: @plan, serializer: V1::PlanSerializer 

那麼它是工作,但我希望它沒有在每一個渲染添加串行工作。

請告訴我解決方案。

回答

0

如果您覆蓋render,它可能會工作。

class ApplicationController < ActionController::API 
    include ActionController::Serialization 
    DEFAULT_SERIALIZER= V1::PlanSerializer 

    def render options, &block 
    options[:serializer]= DEFAULT_SERIALIZER unless options[:serializer] 
    super options, &block 
    end 

end 
+0

根據activemodel的0.10 doc-「當序列化命名空間內的模型,如API :: V1 ::帖子,ActiveModelSerializers會期望相應的序列化是同一個命名空間(即阿比:: V1內: :PostSerializer) 「 – Adt

+0

https://github.com/rails-api/active_model_serializers/blob/master/docs/general/getting_started.md 但它不工作:( – Adt