2017-02-09 67 views
2

我使用的寶石 'active_model_serializers', '〜> 0.10.0' 的formart JSON與寶石versionist的版本API管理如何使用render json:with active-model-serializers gem?

我寫克隆控制器出口JSON是這樣的:

#app/v1/products_controller 
class V1::ProductsController < V1::BaseController 
    start_offset = params[:offset] 
    max_products = Product.all.size 
    products = Product.all.limit(Settings.limit_products_json).offset start_offset 
    next_number = start_offset.to_i + Settings.limit_products_json 

    if next_number < max_products 
    render json: { 
     products: products, 
     next_products: Settings.next_products_json + next_number.to_s, 
     product_end: Settings.product_end_false_json 
    } 
    else 
    render json: { 
     products: products, 
     product_end: Settings.product_end_true_json, 
     product_end_reason: Settings.product_end_reason_json 
    } 
    end 
end 

和串行我寫的文件夾:

#serializers/v1/product_serializer.rb 
class V1::ProductSerializer < ActiveModel::Serializer 
    attributes :id, :name 
end 

並且結果是Product to json的所有屬性。但我只想要:id:name的產品限制結果,正如我在V1::ProductSerializer中所寫的那樣。我怎樣才能做到這一點?對不起,我的英語不好!

回答

1

就我所知,active_model_serializers不支持版本控制。請將您的序列化器重命名爲ProductSerializer或明確指定each_serializer選項,並將其他參數放入meta:

meta = if next_number < max_products 
    { 
    next_products: Settings.next_products_json + next_number.to_s, 
    product_end: Settings.product_end_false_json 
    } 
else 
    { 
    product_end: Settings.product_end_true_json, 
    product_end_reason: Settings.product_end_reason_json 
    } 
end 

render json: products, each_serializer: V1::ProductSerializer, meta: meta