【问题标题】:Pass options to ActiveModelSerializers 0.9.0将选项传递给 ActiveModelSerializers 0.9.0
【发布时间】:2014-11-27 12:01:46
【问题描述】:

有没有办法可以将选项传递给新版本的 AMS,例如 this answer 节目?

【问题讨论】:

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


    【解决方案1】:

    您可以在创建序列化程序的新实例时解析选项Hash,但它将使用的唯一属性是:root,正如您在ActiveModel::Serializer source code 上看到的那样:

    def initialize(object, options = {})
      @object = object
      @root   = options[:root] || (self.class._root ? self.class.root_name : false)
    end
    

    您可以在您的 Serializer 类上覆盖此方法,并根据需要使用其余选项:

    class PostSerializer < ActiveModel::Serializer
      attributes :title, :body
    
      def initialize(object, options = {})
        super(object, options)
        # Your custom code goes here
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 2017-08-13
      • 2011-12-08
      相关资源
      最近更新 更多