Sergio Xalambrí

Tutorial

Use ActiveModel::Serializer with non ActiveRecord object

If you are trying to serialize an object which is not an instance of ActiveRecord, when calling:

UserSerializer.new(data).to_json

You will get this error:

NoMethodError (undefined method `read_attribute_for_serialization' for #<Hash:0x0000000129d34148>)

To fix it, in the serializer add the following method

def read_attribute_for_serialization(attr)
  return object[attr.to_s]
end

Now, if you run the first line again it will correctly return the serializer JSON.

Do you like my content?

Your sponsorship helps me create more tutorials, articles, and open-source tools.

Sponsor me on GitHub