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

ActiveModelSerializers gem: how to pass parameter to serializer


I'm updating the gem active_model_serializers from version 0.9.5 to 0.10.1. For version 0.9.5 the code below worked.

Controller:

def create
  ...
  render json: @dia, app_rights: app_rights(@dia)
end

Serializer:

class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
  attributes :app_rights
  def app_rights
    serialization_options[:app_rights]
  end
end

The method serialization_options has been deprecated in version 0.10.1.

  • Here it is suggested to use instance_options instead.
  • Here it is suggested to use options: "instance_options is only available in the master branch, not in the current RC. In the current RC, you have to use options instead".
  • There are also suggestions for @options and @instance_options.

I have tried replacing serialization_options with all the above options. However, in all cases, after updating the gem, the json produced does not include app_rights. What am I doing wrong?


Solution

  • Using instance_options, your serializer should look like this:

    class Api::V1::SerializerWithSessionMetadata < ActiveModel::Serializer
        attributes :app_rights
        def app_rights
            @instance_options[:app_rights]
        end
    end
    

    To ensure that the correct serializer gets called, you can render a specific serializer like this (otherwise it will render whatever is defined for the class on @dia):

    render json: @dia, serializer: SerializerWithSessionMetadata, app_rights: app_rights(@dia)