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

Rac*_*hel 5 ruby-on-rails active-model-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
Run Code Online (Sandbox Code Playgroud)

我的序列化器:

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
Run Code Online (Sandbox Code Playgroud)

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

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

Was*_*ain 7

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
Run Code Online (Sandbox Code Playgroud)

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

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

文档:将任意选项传递给序列化程序


AMS 版本:0.9.7

不幸的是,对于这个版本的 AMS,没有明确的方式将参数发送到序列化程序。但是你可以使用这个任何类似的关键字的破解:scope如贾迪普说)或:context出的下列访问

attr_accessor :object, :scope, :root, :meta_key, :meta, :key_format, :context, :polymorphic
Run Code Online (Sandbox Code Playgroud)

虽然我宁愿:context:scope像这样这个问题的目的:

在您的控制器中:

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

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

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