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

时间:2017-02-09 12:23:14

标签: ruby-on-rails json ruby active-model-serializers

我使用gem'active_model_serializers','〜>对于带有版本api管理器的gem版本的formart json,0.10.0'

我为导出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文件夹中写道:

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

结果是Product到json的所有属性。但我只希望将产品的结果限制为:id:name,就像我在课程V1::ProductSerializer中所写的那样。我怎样才能做到这一点?抱歉我的英文不好!

1 个答案:

答案 0 :(得分:1)

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