gpt4 book ai didi

ruby-on-rails - 有没有办法通过使用 Rails 中的 Fast JSON API 只选择外部对象的一个​​属性?

转载 作者:行者123 更新时间:2023-12-04 09:41:52 24 4
gpt4 key购买 nike

我正在创建一个使用后端 Rails API 的旅行应用程序。我决定使用 Fast JSON API 来序列化我的数据。我有一份国家 list ;每个国家都有很多城市,每个城市都有很多景点。

这些是我的模型之间的关联列表。

Country.rb 
has_many :cities
has_many :attractions, through: :locality

Localities.rb
has_many :attractions
belongs_to :country

Attraction.rb
belongs_to :locality

当我为单个景点序列化我的数据时,我只想包括城市的名称属性和它所属国家的名称属性。我目前正在通过添加可选参数来包含地点和国家/地区名称来执行此操作。
  def show
attraction = Attraction.find_by(slug: params[:slug])
options = {}
options[:include] = [:locality, :'locality.country.name']
render json: AttractionSerializer.new(attraction, options).serialized_json
end

但是,这给出了该国家/地区的所有属性和关系,包括嵌套在该国家/地区内的所有无关地点的列表,当我的数据集变大时,这将变得非常低效。见下文:
{
"data": {
"id": "1",
"type": "attraction",
"attributes": {
"name": "Plaza de España",
"description": "Site of the World Exposition in 1929",
"types": null,
"latitude": 40.4232824,
"longitude": -3.7107257,
"slug": "plaza-de-espana",
"locality": {
"id": 1,
"name": "Seville",
"country_id": 168,
"created_at": "2020-06-10T05:43:47.474Z",
"updated_at": "2020-06-10T05:43:47.474Z",
"slug": "seville",
"latitude": 37.3886303,
"longitude": -5.9953403
}
},
"relationships": {
"locality": {
"data": {
"id": "1",
"type": "locality"
}
}
}
},
"included": [
{
"id": "1",
"type": "locality",
"attributes": {
"name": "Seville",
"latitude": 37.3886303,
"longitude": -5.9953403,
"slug": "seville"
},
"relationships": {
"country": {
"data": {
"id": "168",
"type": "country"
}
}
}
},
{
"id": "168",
"type": "country",
"attributes": {
"name": "Spain",
"slug": "spain",
"iso_3166_1_alpha2": "ES",
"iso_3166_1_alpha3": "ESP",
"iso_3166_1_numeric": "724"
},
"relationships": {
"localities": {
"data": [
{
"id": "1",
"type": "locality"
},
{
"id": "2",
"type": "locality"
},
{
"id": "3",
"type": "locality"
},
{
"id": "4",
"type": "locality"
},
{
"id": "5",
"type": "locality"
},
{
"id": "6",
"type": "locality"
}
]
},
"attractions": {
"data": [
{
"id": "1",
"type": "attraction"
}
]
}
}
}
]

}

有没有办法在 Attraction JSON 中只包含一个属性(即国家/地区名称),而不是整个对象? (景点嵌套在国家以下两层)

非常感谢。

最佳答案

您需要创建多个协同工作的序列化程序来实现这一点。

class AttractionSerializer
include FastJsonapi::ObjectSerializer

attributes :attraction_attr_1, :attraction_attr_2, etc.

belongs_to :locality, serializer: AttractionLocalitySerializer
end
class AttractionLocalitySerializer
include FastJsonapi::ObjectSerializer

attributes :name

belongs_to :country, serializer: AttractionCountrySerializer
end
class AttractionCountrySerializer
include FastJsonapi::ObjectSerializer

attributes :name
end

关于ruby-on-rails - 有没有办法通过使用 Rails 中的 Fast JSON API 只选择外部对象的一个​​属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62298170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com