ActiveModel Serializer - 将参数传递给序列化器

ActiveModel Serializer - Passing params to serializers

AMS版本:0.9.7

我正在尝试将参数传递给 ActiveModel 序列化程序,但运气不佳。

我的(浓缩)控制器:

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

我的序列化器:

class V1::WatchlistOnlySerializer < ActiveModel::Serializer
  attributes :id, :name, :created_at, :market_value
  attributes :id

  
  def filter(keys)
    keys = {} if object.active == false 
    keys
  end 
  
  private

  def market_value
    # this is where I'm trying to pass the parameter
    currency = "usd"
    Balance.watchlist_market_value(self.id, currency)
  end

我正在尝试将参数 currency 从控制器传递到要在 market_value 方法中使用的序列化程序(在示例中被硬编码为“usd”)。

我试过@options 和@instance_options,但似乎无法正常工作。不确定是否只是语法问题。

您可以像这样将参数发送到序列化程序

render json: @watchlists, each_serializer: WatchlistOnlySerializer, current_params: currency

并且在您的序列化程序中,您可以使用它来获取值

serialization_options[:current_params]

尝试在控制器中使用 scope

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

在你的序列化器中:

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

AMS版本:0.10.6

传递给 render 的任何未保留给 adapter 的选项在序列化程序中都可用 instance_options

在你的控制器中:

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

然后你可以像这样在序列化器中访问它:

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

文档:Passing Arbitrary Options To A Serializer


AMS版本:0.9.7

不幸的是,对于这个版本的 AMS,没有向序列化程序发送参数的明确方法。但是你可以使用任何关键字来解决这个问题,比如 :scope () or :context out of the following accessors:

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

虽然我更喜欢 :context 而不是 :scope 对于这个问题的目的是这样的:

在你的控制器中:

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

然后你可以像这样在序列化器中访问它:

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