提问人:Indyarocks 提问时间:10/22/2023 最后编辑:Indyarocks 更新时间:10/23/2023 访问量:78
jsonapi-serializer - 返回 slug 而不是 id 作为关系
jsonapi-serializer - Return slug instead of id for relationship
问:
我正在使用 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
更新:
有一个 ,可用于覆盖它。id_method_name
belongs_to :seller, id_method_name: :slug
但它会选择产品的蛞蝓,而不是卖家的蛞蝓。
答:
您面临的问题源于如何处理关联。用于指定要对父对象(在本例中为 )调用哪个方法来获取关联的 ID。但是,您希望在关联的对象 () 上调用该方法,以将其作为 ID。jsonapi-serializer
id_method_name
Product
Seller
slug
若要解决此问题,可以覆盖关联的默认行为。这是一个解决方案:
将 a 与 中的关联一起使用。在块中,您可以显式定义关联的属性。通过指定关联的属性,可以控制在序列化输出中将哪个值用作关联的 ID。
block
belongs_to
ProductSerializer
id
在块内,对关联的对象调用该方法以检索其 .
slug
Seller
slug
以下是修改 以实现此目的的方法:ProductSerializer
class ProductSerializer < V1::BaseSerializer
set_id :slug
set_type :product
attributes :name, :description, :original_price_cents, :discounted_price_cents
belongs_to :seller do |object|
{ id: object.seller.slug, type: :seller }
end
end
通过此更改,关联将使用关联对象的 ID 作为序列化输出中的 ID。belongs_to :seller
slug
Seller
注意:确保模型与(例如,在模型中)具有关联,并且模型具有属性或方法。Product
Seller
belongs_to :seller
Product
Seller
slug
评论