Marty
Marty

Reputation: 2224

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.

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?

Upvotes: 2

Views: 1620

Answers (1)

johnstoecker
johnstoecker

Reputation: 248

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)

Upvotes: 5

Related Questions