0

I have the following serializers:

class V1::CategorySerializer < ActiveModel::Serializer
  has_one :category_name, :class_name => 'V1::CategoryName'
  has_many :brands, :class_name => 'V1::Brand'
end

class V1::CategoryNameSerializer < ActiveModel::Serializer
  attributes :name
  has_many :brand_names, :class_name => 'V1::BrandName'
end

class V1::BrandSerializer < ActiveModel::Serializer
  has_one :brand_name, :class_name => 'V1::BrandName'
end

class V1::BrandNameSerializer < ActiveModel::Serializer
  attributes :name
end

When I render via Category render json: seller.categories I do not want the BrandNames to be printed. Output should be something like:

{
  "seller_id": 1,
  "categories" :
  [
    {
    "name" : "Washing Machines",
    "brands" : ["LG", "Samsung"]
    }
  ]
}

instead of

{
    "brands_categories": [
        {
            "category_name": {
                "name": "Washing Machines",
                "brand_names": [
                    {
                        "name": "LG"
                    },
                    {
                        "name": "Samsung"
                    }
                ]
            },
            "brands": [
                {
                    "brand_name": {
                        "name": "LG"
                    }
                },
                {
                    "brand_name": {
                        "name": "Samsung"
                    }
                }
            ]
        }
    ]
}

Also, I want to keep the current behavior of printing render json: V1::CategoryName.all as it is.

Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89

1 Answers1

0

I solved my problem by changing the CategorySerializer to

class V1::CategorySerializer < ActiveModel::Serializer
  attributes :category, :brands

  def category
    object.category_name.name
  end

  def brands
    brand_names = []
    object.brands.each do |brand|
      brand_names << brand.brand_name[:name]
    end
    brand_names
  end
end
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89