ActiveModel Serializer - Passing params to serializers

AMS version: 0.10.6

Any options passed to render that are not reserved for the adapter are available in the serializer as instance_options.

In your controller:

def index
  @watchlists = Watchlist.belongs_to_user(current_user)
  render json: @watchlists, each_serializer: WatchlistOnlySerializer, currency: params[:currency]
end

Then you can access it in the serializer like so:

def market_value
  # this is where I'm trying to pass the parameter
  Balance.watchlist_market_value(self.id, instance_options[:currency])
end

Doc: Passing Arbitrary Options To A Serializer


AMS version: 0.9.7

Unfortunately for this version of AMS, there is no clear way of sending parameters to the serializer. But you can hack this using any of the keywords like :scope (as Jagdeep said) or :context out of the following accessors:

attr_accessor :object, :scope, :root, :meta_key, :meta, :key_format, :context, :polymorphic

Though I would prefer :context over :scope for the purpose of this question like so:

In your controller:

def index
  @watchlists = Watchlist.belongs_to_user(current_user)
  render json: @watchlists,
    each_serializer: WatchlistOnlySerializer,
    context: { currency: params[:currency] }
end

Then you can access it in the serializer like so:

def market_value
  # this is where I'm trying to pass the parameter
  Balance.watchlist_market_value(self.id, context[:currency])
end

Try using scope in controller:

def index
 @watchlists = Watchlist.belongs_to_user(current_user)
 render json: @watchlists, each_serializer: WatchlistOnlySerializer, scope: { currency: params[:currency] }
end

And in your serializer:

def market_value
  Balance.watchlist_market_value(self.id, scope[:currency])
end