2016-04-01 15 views
1

私は次のシリアライザクラスを持っている:ActiveModelシリアライザのカスタム属性をオブジェクトパラメータで定義する方法は?

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 
関連する問題