我刚刚开始研究在rails中进行序列化,并且在将其设置为嵌套多态关联时遇到问题。
在我的购物Rails API中,我具有以下关联:
### Cart model
class Cart < ApplicationRecord
has_many :discounts
end
### Discount model
class Discount < ApplicationRecord
belongs_to :cart
belongs_to :discountable, polymorphic: true
end
### Extras model (extra meaning you get 3 items for price of 2)
class Extra < ApplicationRecord
has_many :discounts, as: :discountable
end
我使用序列化程序实现的是:
### Cart serializer
class CartSerializer < ActiveModel::Serializer
has_many :discounts
end
### Discount serializer
class DiscountSerializer < ActiveModel::Serializer
attribute :discountable, polymorphic: true
end
这反过来给了我这个json:
{
"discounts": [
{
"discountable": {
"id": 1,
"kind": "extra",
"name": "Grill Set",
"product_ids": [
1,
2,
3
],
"count": 2,
"created_at": "2019-05-11T17:09:44.366Z",
"updated_at": "2019-05-11T17:09:44.366Z"
}
}
]
}
但是我对此不太满意-我想省略created_at和updated_at属性,并将折扣一一列出(没有可打折嵌套)。
类似这样的东西:
{
"discounts": [
{
"id": 1,
"kind": "extra",
"name": "Grill Set",
"product_ids": [
1,
2,
3
],
"count": 2,
}
]
}
很高兴获得帮助。