unknown
unknown

Reputation: 110

Rails Active Model Serializers has_many

I'm using ActiveModelSerializers gem. In my model a User can have many Vehicles

class User < ActiveRecord::Base
   has_many :vehicles
end

class Vehicle < ActiveRecord::Base
   belongs_to :user
end

My serializers:

class UserSerializer < ActiveModel::Serializer
  attributes :name, :vehicles
end

class VehicleSerializer < ActiveModel::Serializer
   attributes :color, :make, :model
end

Vehicle has more attributes than just color, make and model.

If I print a single vehicle @vehicle, then only the fields specified in serializer are displayed. However, if I print @user (which includes :vehicles in it's serializer) then the serializer is ignored and all the fields of Vehicle are printed.

I'm guessing it has to to with the fact that user.vehicles is an array and not just one item, but is there a way to print the whole array of a user's vehicles as described in serializer for each item?

Regards.

Upvotes: 0

Views: 1695

Answers (1)

Zachary Friedman
Zachary Friedman

Reputation: 109

AMS supports associations through the ActiveModel::Serializer::Association struct. What this means is that you can have in your UserSerializer the following:

class UserSerializer < ActiveModel::Serializer
  attributes :name

  has_many :vehicles
end

Upvotes: 5

Related Questions