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
中所寫的那樣。我怎樣才能做到這一點?對不起,我的英語不好!