0
我有以下串行:在ActiveModelSerializer渲染的has_many有條件
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
類別渲染我不希望打印的品牌名稱做。輸出應該是這樣的:的
{
"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
,因爲它是當前的行爲。
我「米將做同樣的事情。這真的是最好的選擇嗎?感覺不雅。 – 2015-05-12 16:51:14
如果輸出固定在你的心中,然後這個是最好的** **大多數**優雅的是使用默認的軌道輸出,即沒有任何串行器 – vedant1811 2015-05-12 19:15:41