Search code examples
ruby-on-railsrubyjsonserializer

ActiveModelSerializer not serialize object nested children


I have a model Category that use awesome_nested_set gem, so it has children of the model itself. I have created CategorySerializer for the model

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

  def children
    object.children
  end
end

But children is not serialized. I have also tried add has_many :children, serializer: self, the result is this

{
        "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 is successfully serialized but it children is not. Is there a way or alternative to serialize all object children?


Solution

  • If you want deep nesting by default, then you can set following config property in the initializer file

    # config/initializers/active_model_serializer.rb    
    ActiveModelSerializers.config.default_includes = '**
    

    For more details, you can check this.

    You can also add another serializer for children as follow

    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
    

    For more information, you can refer to this link