[英]How to define custom attributes for ActiveModel Serializer by object params?
我有以下序列化程序类:
class BooksSerializer < ActiveModel::Serializer
attributes :name, :position
attributes :pages unless object.children.present?
但它因错误“SectionSerializer:Class 的未定义方法‘对象’”而失败。 如何获取这些条件的对象参数?
我只能在函数内部访问对象。 例如:
def pages
object.pages ....
end
但是我需要按条件从序列化中排除一些字段。
我找到了一个解决方案:
class BooksSerializer < ActiveModel::Serializer
attributes :name
def attributes(*args)
hash = super
hash[:pages] = pages unless object.children.present?
hash
end
def pages
....
end
....
end
这是一个更新的解决方案:
class BooksSerializer < ActiveModel::Serializer
attributes :name
attribute :pages, if: -> { object.children.present? }
def pages
...
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.