如何使用 render json: 与 active-model-serializers gem?

how to use render json: with active-model-serializers gem?

我使用 gem 'active_model_serializers','~> 0.10.0' 用于格式 json,gem 版本主义者用于版本 api 管理器

我像这样为导出 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

结果是 json 的 Product 的所有属性。但我只想将产品结果限制为 :id:name,正如我在 class V1::ProductSerializer 中所写的那样。我怎样才能做到这一点?抱歉我的英语不好!

据我所知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