ActiveModelSerializer 不序列化对象嵌套子项

ActiveModelSerializer not serialize object nested children

我有一个使用 awesome_nested_set gem 的模型类别,因此它有模型本身的子项。我为模型创建了 CategorySerializer

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :parent_id, :lft, :rgt, :text, :permalink, :children

  def children
    object.children
  end
end

但是children没有连载。我也试过添加has_many :children, serializer: self,结果是这样

{
        "id": 25918,
        "parent_id": null,
        "lft": 3,
        "rgt": 8,
        "text": "ARAG",
        "permalink": "25918-arag",
        "children": [
            {
                "id": 25919,
                "parent_id": 25918,
                "lft": 4,
                "rgt": 7,
                "text": "Coperchi",
                "permalink": "25919-coperchi",
                "children": [
                    {
                        "id": 25920,
                        "parent_id": 25919,
                        "lft": 5,
                        "rgt": 6,
                        "text": "Ribaltabili",
                        "description": "",
                        "page_title": "",
                        "meta_key": "",
                        "meta_description": "",
                        "key_1": null,
                        "key_2": null,
                        "key_3": null,
                        "extra": null,
                        "created_at": "2019-03-01T21:08:15.000+01:00",
                        "updated_at": "2019-04-02T12:27:05.000+02:00"
                    }
                ]
            }
        ]
    }

second level of children 已成功序列化,但 children 没有。有没有一种方法或替代方法来序列化所有对象子对象?

这个在 children 上调用序列化程序的解决方案怎么样?小心不要陷入深度嵌套的无限循环

def children
  object.children.map { |obj| SomeSerializer.new(obj) }
end

如果你想要默认深度嵌套,那么你可以在初始化文件

中设置以下配置属性
# config/initializers/active_model_serializer.rb    
ActiveModelSerializers.config.default_includes = '**

更多详情,您可以查看this

您还可以为 children 添加另一个序列化程序,如下所示

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :parent_id, :lft, :rgt, :text, :permalink, :children

  def children
    ActiveModel::SerializableResource.new(object.children,  each_serializer: ChildrenSerializer)
  end
end

更多信息可以参考这篇link