【问题标题】:How to define custom attributes for ActiveModel Serializer by object params?如何通过对象参数为 ActiveModel Serializer 定义自定义属性?
【发布时间】:2016-07-21 16:21:04
【问题描述】:
我有以下序列化程序类:
class BooksSerializer < ActiveModel::Serializer
attributes :name, :position
attributes :pages unless object.children.present?
但它出现了错误“SectionSerializer:Class 的未定义方法 `object'”。如何获取这些条件的对象参数?
我只能在函数内部访问对象。例如:
def pages
object.pages ....
end
但我需要从条件序列化中排除一些字段。
【问题讨论】:
标签:
ruby-on-rails
activemodel
serialization
【解决方案1】:
我找到了解决办法:
class BooksSerializer < ActiveModel::Serializer
attributes :name
def attributes(*args)
hash = super
hash[:pages] = pages unless object.children.present?
hash
end
def pages
....
end
....
end
【解决方案2】:
这是一个更新的解决方案:
class BooksSerializer < ActiveModel::Serializer
attributes :name
attribute :pages, if: -> { object.children.present? }
def pages
...
end
end