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

How to return all attributes of an object with Rails Serializer?


I have a simple question. I have a seriaizer that looks like this:

class GroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :about, :city 
end

The problem is that, whenever I change my model, I have to add/remove attributes from this serializer. I just want to get the whole object by default as in the default rails json respond:

render json: @group

How can I do that?


Solution

  • At least on 0.8.2 of ActiveModelSerializers you can use the following:

    class GroupSerializer < ActiveModel::Serializer
      def attributes
        object.attributes.symbolize_keys
      end
    end
    

    Be carful with this though as it will add every attribute that your object has attached to it. You probably will want to put in some filtering logic on your serializer to prevent sensitive information from being shown (i.e., encrypted passwords, etc...)

    This does not address associations, although with a little digging around you could probably implement something similar.

    ============================================================

    UPDATE: 01/12/2016

    On 0.10.x version of ActiveModelSerializers, attributes receives two arguments by default. I added *args to avoid exception:

    class GroupSerializer < ActiveModel::Serializer
      def attributes(*args)
        object.attributes.symbolize_keys
      end
    end