我在我的ActiveModel::Serializer
下面的代碼片段。這是一種遞歸方法,但我需要添加到遞歸結束時返回的數組中。ActiveModel :: Serializer實例變量在方法中無法訪問
所以,我設置了一個實例變量@rows
等於一個空數組[]
。我在該方法中推入該數組,但Ruby正在返回一個undefined method 'push' for nil:NilClass
。
class MySerializer < ActiveModel::Serializer
attributes :hierarchies
@rows = []
def hierarchies_run(child, user)
hierarchy = UserHierarchy.where(child: child, user_id: user).first
if hierarchy
@rows.push(UserSimpleSerializer.new(User.find(hierarchy.child), :root => false))
hierarchies_run(hierarchy.parent, current.id)
else
@rows.push(UserSimpleSerializer.new(User.find(child), :root => false))
end
end
def hierarchies
hierarchies_run(current.id, current.id)
@rows
end
end
爲什麼它返回這個錯誤?
請出示您的所有代碼 –
的這一切的代碼,但包裝在'class MySerializer
Noah
對,你的更新解釋了這個問題,這就是爲什麼我要求更多的代碼。您正在類範圍內定義'@ rows',而不是實例範圍,因爲實例變量默認爲'nil','@ rows'在任何實例方法中都是'nil'。你應該在構造函數中定義它 –