Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
Salah Saleh Avatar asked Mar 27 '15 11:03

Salah Saleh


2 Answers

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
like image 176
Kevin Jalbert Avatar answered Nov 17 '22 03:11

Kevin Jalbert


Just to add to @kevin's answer. I was looking also to how to add filters on the returned attributes. I looked to the the documentation active_model_serializers 0.9 and it does support filters that looks like this:

  def attributes
    object.attributes.symbolize_keys
  end
  def filter(keys)
          keys - [:author, :id]
  end

I tried it, but it did not work. I assumed that's because the attributes are not specified explicitly. I had to do it the same way specified in the rails cast to work:

@@except=[:author, :id]
def attributes
    data = object.attributes.symbolize_keys
    @@except.each { |e| data.delete e  }
    data
end
like image 1
Salah Saleh Avatar answered Nov 17 '22 04:11

Salah Saleh