[英]Having trouble accessing a field of a field if the first field is nil in Rails
[英]Having trouble accessing nested data and Nil in Ruby/Rails
我正在Rails應用程序中從外部API獲取數據以進行React前端。 我想在數據到達前端之前清理數據,並嘗試在不可預測的API響應中到達嵌套數據。 有時,嵌套數據返回某些內容,而其他時候則返回nil
。 這是問題(我認為)。
我嘗試了有條件的各種保護措施,但這似乎不起作用。
這是我正在使用的方法:
def song_details
search = HTTParty.get("https://musicbrainz.org/ws/2/release/#{params[:songId]}?inc=artist-credits+artist-rels+media+recording-level-rels+url-rels+work-level-rels+recording-rels&fmt=json", {
headers: {"User-Agent" => "Songly/ver 1.0", "Contact" => "demiansims@gmail.com"}
})
end
如果在Rails控制台中調用search['relations'][0]['artist']['name']
,我會得到一個漂亮的名稱字符串。
如果我嘗試運行:
search['relations'].map { |r| r['artist'].each { |a| puts a['name'] }}
no method for Nil class on []
錯誤,我no method for Nil class on []
。 我知道這是因為某些值是Nil。
這是嵌套數據的完整圖片(價值1次迭代-其中約有20種):
{"end"=>nil,
"attribute-values"=>{},
"artist"=>
{"id"=>"70047e57-0153-4117-b0fc-a1d2e322e5ef",
"name"=>"Donald Fagen",
"disambiguation"=>"",
"sort-name"=>"Fagen, Donald"},
"ended"=>false,
"direction"=>"backward",
"type-id"=>"01ce32b0-d873-4baa-8025-714b45c0c754",
"begin"=>nil,
"target-type"=>"artist",
"target-credit"=>"",
"type"=>"composer",
"attributes"=>[],
"attribute-ids"=>{},
"source-credit"=>""}
我試圖從relations -> artist -> name
獲取名稱relations -> artist -> name
,即使有一個“藝術家”或“名稱”並且它不等於nil。 我該如何處理? 抱歉,我是Rails的新手,剛開始嘗試使用數據結構。 我認為我在發送到React之前處理好后端中的數據是正確的嗎?
編輯
以下建議更加接近,但嘗試包裝數據時仍然出現錯誤:
def song_details
search = HTTParty.get("https://musicbrainz.org/ws/2/release/#{params[:songId]}?inc=artist-credits+artist-rels+media+recording-level-rels+url-rels+work-level-rels+recording-rels&fmt=json", {
headers: {"User-Agent" => "Songly/ver 1.0", "Contact" => "demiansims@gmail.com"}
})
search['relations'].present?
search['relations'].map do |r|
r['artist'].present?
artist = {
name: r['artist', 'name'],
role: r['type'].present? && r['type'],
id: r['artist', 'id'],
disambiguation: r['artist', 'disambiguation'],
attributes: r['attributes'] && r['attributes'].each { |a| a }
}
end
artist
end
我收到如下錯誤:
app/controllers/api/v1/searches_controller.rb:26:in `[]'
app/controllers/api/v1/searches_controller.rb:26:in `block in song_details'
app/controllers/api/v1/searches_controller.rb:21:in `map'
app/controllers/api/v1/searches_controller.rb:21:in `song_details'
這是一個很好的示例,您可以在其中使用Hash#dig
artist_names = search['relations'].map { |r| r.dig('artist', 'name') }
您可以在rails中使用try方法try方法返回nil如果對象中不存在數據,請參考此鏈接以供參考,如果不起作用,請使用a.present?
類的nil檢查a.present?
還是a.blank?
如果要檢查nil,則使用提供的示例並假定將其放在數組中,可以使用
a.map { |r| r['artist'] && r['artist']['name'] } //a is array of object you specified
您做錯了r ['artist','name']拋出錯誤
def song_details
search = HTTParty.get("https://musicbrainz.org/ws/2/release/#{params[:songId]}?inc=artist-credits+artist-rels+media+recording-level-rels+url-rels+work-level-rels+recording-rels&fmt=json", {
headers: {"User-Agent" => "Songly/ver 1.0", "Contact" => "demiansims@gmail.com"}
})
search['relations'].present?
search['relations'].map do |r|
r['artist'].present?
artist = {
name: r.dig('artist', 'name'),
role: r['type'],
id: r.dig('artist', 'id'),
disambiguation: r.dig('artist', 'disambiguation'),
attributes: r['attributes'] && r['attributes'].each { |a| a }
}
end
artist
結束
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.