Search code examples
ruby-on-railsjsonrubyactive-model-serializers

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


i use gem 'active_model_serializers', '~> 0.10.0' for formart json with gem versionist for version api manager

i write clone controller for export json like this :

#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

and in serializers folder i write:

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

and result is all attributes of Product to json. But I only want limit result of product to :id and :name as i wrote in class V1::ProductSerializer. How can i do that? Sorry for my bad english!


Solution

  • As far as I know active_model_serializers does not support versioning out of box. Either rename your serializer to ProductSerializer or specify each_serializer option explicitly and put your other parameters in 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