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

Get an ActiveModel::Serializer instance for an arbitrary (type unknown) model instance


If I have an instance of a Project model and I want to serialize it into an arbitrary hash using active_model_serializer, I can do this:

render :json => {:foo => "bar", :model => ProjectSerializer.new(my_project).as_json}

But in my scenario, I don't know the type of my model instance ahead of time so I need to determine the right serializer polymorphically. Poking around the active_model_serializer code, I see internally it uses ActiveModel::Serializer.serializer_for but this isn't callable from a controller for some reason. I can make it work like this:

begin
   serializer = Object.const_get "#{model.name}Serializer"
   object_hash = serializer.new(model).as_json
rescue NameError
   object_hash = model.as_json
end

This works fine, but I'd rather my code not concern itself with this detail of the serializer. Is there a "right" way to find the serializer for an arbitrary model?


Solution

  • Try:

    model_instance.active_model_serializer
    

    I am not sure why this is not documented but it is in the code and it works.