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

ActiveModel Serializers changing output for associated models' parameters


this is what the serializer for Event looks like now

class EventSerializer < ActiveModel::Serializer
  attributes :name, :venue, :artists
end

the output I get is

[{"name":"Dance your ass off",
  "venue":{"id":21,"name":"Speakeasy","address":"Lynwood Ave","zip_code":30312,"created_at":"2016-03-24T18:13:03.032Z","updated_at":"2016-03-24T18:13:03.032Z"},
  "artists":[{"id":41,"name":"DJ Sliink","bio":"jersey club king","created_at":"2016-03-24T18:13:03.067Z","updated_at":"2016-03-24T18:13:03.067Z"},{"id":42,"name":"DJ Spinn","bio":"Teklife's chief spokesperson","created_at":"2016-03-24T18:13:03.072Z","updated_at":"2016-03-24T18:13:03.072Z"}]}]

how do I change this to showing just the names of venue and artists?


Solution

  • You can define custom methods for those required attributes as shown below:

    class EventSerializer < ActiveModel::Serializer
      attributes :name, :venue, :artists
    
      def name
         object.name
      end
    
      def venue
         object.venue.name
      end
    
      def artists
         object.artists.map(&:name)
      end
    end
    

    You can refer the AMS docs for further information.