Rails: rendering json with multiple objects

3.9k views Asked by At

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?

2

There are 2 answers

1
Hai Nguyen On BEST ANSWER

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
0
Kishan Ku. Patel On

The following code snippet works for me, reference link https://github.com/rails-api/active_model_serializers/issues/1091#issuecomment-477015183

def index
  @beers = Beer.all
  @micros = Micros.all

  render json: {
     beers: ActiveModelSerializers::SerializableResource.new(@beers, each_serializer: BeerSerializer),
     micros: ActiveModelSerializers::SerializableResource.new(@micros, each_serializer: MicroSerializer),
  }
end

To check in console: just put .as_json

ActiveModelSerializers::SerializableResource.new(@beers, each_serializer: BeerSerializer).as_json