Use active_model_serializer with a non-ActiveRecord object

Robin Daugherty picture Robin Daugherty · Feb 11, 2014 · Viewed 9k times · Source

I have a model object that is not descended from ActiveRecord::Base and is not stored in the database. I created a serializer for it (with the same name + "Serializer"), and in my controller I'm calling render json: object_instance.

The result is an exception from deep inside of render.

I implemented an as_json method that instantiates the serializer and calls it, but the result is then a missing method in the object, read_attribute_for_serialization.

I want my object to act like an ActiveModel-compatible object at least as far as Active Model Serializer goes, but I don't see any reference to this in their documentation.

Answer

Robin Daugherty picture Robin Daugherty · Feb 11, 2014

The model object needs to include it thusly:

# active_model_serializers 0.10+
class ModelName
  include ActiveModel::Serialization
end

# active_model_serializers < 0.10
class ModelName
  include ActiveModel::SerializerSupport
end

This implements the methods needed within the object, and also auto-discovers the serializer matching the object name, so it can be used transparently just like an ActiveRecord object.

This works with active_model_serializers version 0.8.1 through at least 0.9.3.