我得到了一个参数,例如: Grape::API中的member_id
desc 'Return Events'
params do
requires :member_id, type: Integer, desc: 'Member'
end
get 'all' do
#some code
end
end
我想把它传递给ActiveModel::Serializer
,这样我就可以执行一些功能了。
有什么方法可以把它传递给ActiveModel::Serializer
吗?
发布于 2016-10-07 23:04:54
当您使用ActiveModel::Serializers
序列化对象时,您可以传递序列化程序中可用的选项,作为options
(或instance_options
,或context
,depending on which version of AMS you're using)。
例如,在Rails中,您可以像这样传递一个foo
选项:
# 0.8.x or 0.10.x
render @my_model, foo: true
MyModelSerializer.new(@my_model, foo: true).as_json
# 0.9.x
render @my_model, context: { foo: true }
MyModelSerializer.new(@my_model, context: { foo: true }).as_json
在序列化程序中,您可以访问options
(或instance_options
)来获取值:
class MyModelSerializer < ActiveModel::Serializer
attributes :my_attribute
def my_attribute
# 0.8.x: options
# 0.9.x: context
# 0.10.x: instance_options
if options[:foo] == true
"foo was set"
end
end
def
https://stackoverflow.com/questions/38977681
复制相似问题