我有以下序列化程序:
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
的当前行为。
答案 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