ActiveModel Serializer - 将参数传递给序列化器 [英] ActiveModel Serializer - Passing params to serializers
问题描述
AMS 版本:0.9.7
我试图将参数传递给 ActiveModel 序列化程序,但没有任何运气.
I am trying to pass a parameter to an ActiveModel serializer without any luck.
我的(精简)控制器:
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
方法中使用(在示例中硬编码为;美元").
I am trying to pass a parameter currency
from the controller to the serializer to be used in the market_value
method (which in the example is hard-coded as "usd").
我已经尝试过@options 和@instance_options,但我似乎无法让它工作.不确定是否只是语法问题.
I've tried @options and @instance_options but I cant seem to get it work. Not sure if its just a syntax issue.
推荐答案
AMS 版本:0.10.6
传递给 render
的任何不为 adapter
保留的选项都可以在序列化程序中作为 instance_options
使用.
Any options passed to render
that are not reserved for the adapter
are available in the serializer as instance_options
.
在您的控制器中:
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
文档:传递任意选项到序列化程序
AMS 版本:0.9.7
不幸的是,对于此版本的 AMS,没有明确的方式将参数发送到序列化程序.但是您可以使用任何关键字来破解它,例如 :scope
(正如 Jagdeep 所说)或:context
来自 以下访问者:
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
虽然我更喜欢 :context
而不是 :scope
来解决这个问题:
Though I would prefer :context
over :scope
for the purpose of this question like so:
在您的控制器中:
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
这篇关于ActiveModel Serializer - 将参数传递给序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!