2016-04-01 18 views
1

我有以下的串行类:如何通过对象参数为ActiveModel Serializer定义自定义属性?

class BooksSerializer < ActiveModel::Serializer 
    attributes :name, :position 
    attributes :pages unless object.children.present? 

但它的坠落下来的错误“未定义的方法'对象”为SectionSerializer:类”。我怎样才能得到这些条件的物体参数?

我只能访问函数内部的对象。例如:

def pages 
    object.pages .... 
end 

但我需要通过条件从序列化中排除一些字段。

回答

2

我找到了一个解决方案:

class BooksSerializer < ActiveModel::Serializer 
    attributes :name 
    def attributes(*args) 
     hash = super 
     hash[:pages] = pages unless object.children.present?   
     hash 
    end 

    def pages 
    .... 
    end 
    .... 
end