【问题标题】:Default serializer render options in Rails controllerRails 控制器中的默认序列化程序渲染选项
【发布时间】:2014-09-13 13:30:10
【问题描述】:

我在 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 调用设置默认选项列表,而不是手动将选项放入每个控制器操作中? p>

【问题讨论】:

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


    【解决方案1】:

    这可以通过将此方法添加到您的控制器来完成:

    def default_serializer_options  
      {user: current_user}  
    end
    

    然后您可以通过options[:user]从序列化程序中访问它

    【讨论】:

    • 这已在 0.10.x 中被删除(未弃用)
    猜你喜欢
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多