ruby-on-railsactive-model-serializers

¿How to use a serializer for @record.all?


I have a Kit model with it's serializer:

class KitSerializer < ActiveModel::Serializer
  attributes :id, :name, :description
  has_many :products, only: [:id, :price]
end

I need to use this serializer to render all of my Kits like this:

  def kits_json
    @kits = Kit.all
    render json: @kits, serializer: KitSerializer
  end

My route

get '/api/kits', to: 'kits#kits_json'

I get an error:

undefined method `model_name' for Kit::ActiveRecord_Relation:Class

It's my first time with serializers, what am I missing?


Solution

  • Since @kits is an array of objects, you should use each_serializer instead of serializer

    your controller will look like as:

    def kits_json
      @kits = Kit.all
      render json: @kits, each_serializer: KitSerializer
    end
    

    If you wanna pass render array of json you can use it as below:

    def kits_json
      @kits = Kit.all
      render json: [ActiveModel::Serializer::CollectionSerializer.new(@kits, serializer: KitSerializer)]
    end