有条件地在ActiveModelSerializer中渲染has_many

时间:2014-10-22 08:30:38

标签: ruby-on-rails active-model-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

当我通过类别render json: seller.categories呈现时,我不希望打印BrandNames。输出应该是这样的:

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

而不是

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

另外,我想保持打印render json: V1::CategoryName.all的当前行为。

1 个答案:

答案 0 :(得分:0)

我通过将CategorySerializer更改为

来解决了我的问题
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