我将 gem 'active_model_serializers', '~> 0.10.0' 用于 formart json,将 gem versionist 用于版本 api 管理器
我像这样为导出 json 编写克隆 Controller :
#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
result是Product的所有属性转json。但我只想将产品结果限制为 :id
和 :name
,正如我在类 V1::ProductSerializer
中所写的那样。我怎样才能做到这一点?抱歉我的英语不好!
最佳答案
据我所知,active_model_serializers 不支持开箱即用的版本控制。将序列化程序重命名为 ProductSerializer
或明确指定 each_serializer
选项并将其他参数放入元数据中:
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
关于ruby-on-rails - 如何使用渲染 json : with active-model-serializers gem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136635/