ruby-on-railsjsonrubyactive-model-serializersapplicationcontroller

Rails: rendering json with multiple objects


I am trying to return multiple objects with the call:

def index
    beers = Beer.all
    micros = Micros.all
    render json: {beers: beers, micro: micros}  
end

However, for both objects is only returning the attributes listed in the respected serializers, not any of the has_many, belongs_to, etc. relationships in the respected serializers.

If I am just trying to return one single object, such as:

def index
    beers = Beer.all
    render json: beers 
end

Then it works fine and returns all the relationships listed in the serializer.

How do I fix the call with multiple objects to return everything in the serializer, not just the attributes?


Solution

  • hope to help you

    def index
      @beers = Beer.all
      @micros = Micros.all
    
      render json: {
         beers: ActiveModel::Serializer::CollectionSerializer.new(@beers, each_serializer: BeerSerializer),
         micros: ActiveModel::Serializer::CollectionSerializer.new(@micros, each_serializer: MicroSerializer),
      }
    end