ruby-on-railsjsonserializationactive-model-serializers

Attempting to upgrade rails dependencies causes serializers to raise error: undefined method `model_name' for Hash:Clas


I have upgraded rails to 5.2.4.2 on a established rails application a few months ago with minimum rails dependency upgrades; The application has stabilised once more so we decided to upgrade all the rails dependencies to its latest compatible versions.

Now, whenever a controller has a json render call to a simple (non db-model) class an error message is presented.

example

This is the serializer:

class Api::MessageResponseSerializer < ApplicationSerializer
  self.version = 1

  attributes :message, :changes

  def message
    self.object[:message]
  end

  def changes
    self.object[:changes]
  end
end

calling

render :json => { :message => "Not Ready Yet"}, :serializer => Api::MessageResponseSerializer

I get the error:

NoMethodError:
       undefined method `model_name' for Hash:Class

calling

render :json => [{ :message => "Not Ready Yet"}], :serializer => Api::MessageResponseSerializer

I get the error:

 NoMethodError:
       undefined method `model_name' for Array:Class

calling (i know this one is not correct json, it is here just to exemplify that the same error occurs)

render :json => 1, :serializer => Api::MessageResponseSerializer

I get the error:

NoMethodError:
       undefined method `model_name' for Integer:Class

I can monkey-patch the classes, but I would rather have a solution to allow the serializers to get the model_name from these simple classes.


Solution

  • It seems there is a hard requirement on having a root key for JSON serialization, introduced as part of the active_model_serializers gem on version 0.10.10 (which was automatically set by bundle upgrade);

    I downgraded this gem to version 0.10.9 and the serialization issues stopped happening...