简体   繁体   English

如何通过对象参数为 ActiveModel Serializer 定义自定义属性?

[英]How to define custom attributes for ActiveModel Serializer by object params?

I have the following Serializer class:我有以下序列化程序类:

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

But it's fall down with an Error "undefined method `object' for SectionSerializer:Class".但它因错误“SectionSerializer:Class 的未定义方法‘对象’”而失败。 How can I get object params for these conditions?如何获取这些条件的对象参数?

I can get access to object only inside of function.我只能在函数内部访问对象。 For example:例如:

def pages
  object.pages  ....
end

But I need to exclude some fields from Serialization by conditions.但是我需要按条件从序列化中排除一些字段。

I found a solution:我找到了一个解决方案:

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

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

Here's an updated solution:这是一个更新的解决方案:

class BooksSerializer < ActiveModel::Serializer
  attributes :name
  attribute :pages, if: -> { object.children.present? }

  def pages
    ...
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM