我正在使用 jsonapi-serializer 来序列化我的对象。
我想返回
slug
原始模型以及所有关联(关系)。
product_serializer.rb
class ProductSerializer < V1::BaseSerializer
set_id :slug
set_type :product
attributes :name, :description, :original_price_cents, :discounted_price_cents
belongs_to :seller
end
seller_serializer.rb
class SellerSerializer < V1::BaseSerializer
set_id :slug
set_type :seller
attributes :average_rating, :reviews_count, :total_sold_count, :name
end
问题是,与卖家的关联正在返回卖家的 ID。
"data": {
"id": "sleek-leather-keyboard-women-s-fashion-shoes",
"type": "product",
"attributes": {
"name": "Sleek Leather Keyboard",
"description": "Non qui est. Est quis molestiae.",
"original_price_cents": 7662,
"discounted_price_cents": 5103,
},
"relationships": {
"seller": {
"data": {
"id": "1",
"type": "seller"
}
},
}
},
我想在上面的回复中隐藏卖家的 ID
1
。我尝试了一些方法,但似乎没有任何帮助。大家有什么建议吗?
不起作用
class ProductSerializer
belongs_to :seller do |serializer, seller|
serializer.slug_for(seller)
end
private
def self.slug_for(relationship)
{ id: relationship.slug }
end
end
这有效:
class ProductSerializer
set_id :slug
set_type :product
attributes :name, :description, :original_price_cents, :discounted_price_cents
belongs_to :seller, id_method_name: :slug
end