Rails控制器中的默认序列化程序渲染选项

时间:2014-09-13 13:30:11

标签: ruby-on-rails json actioncontroller active-model-serializers

我在rails项目中使用Active Model Serializers并且有一个user对象需要从控制器传递到序列化器,如下所示:

# Note the 'user:' option that will be accessible inside
# the serializer with @options[:user]
def show
render json: @some_object, user: current_user
end

def index
render json: SomeObject.all, user: current_user
end

这对我正在尝试做的事情来说已经足够了,但它不是很干,导致render语句充斥着选项。当这些选项发生变化时,我需要返回并在所有操作中手动删除/修改它们。

我的问题是:有没有办法在控制器级别为render调用设置默认选项列表,而不是手动将选项放在每个控制器操作中?

1 个答案:

答案 0 :(得分:3)

这可以通过将此方法添加到控制器来实现:

def default_serializer_options  
  {user: current_user}  
end

然后,您可以通过options[:user]

从序列化程序中访问它