Ruby on rails Ruby:“是的。”;未定义的方法“[]';对于nil:NilClass“;在for循环中
我正在尝试使用for循环和JSON解析填充我的数据库。当我不尝试for循环,而只是对单个对象执行时,它就工作了。这是我的密码:Ruby on rails Ruby:“是的。”;未定义的方法“[]';对于nil:NilClass“;在for循环中,ruby-on-rails,ruby,json,Ruby On Rails,Ruby,Json,我正在尝试使用for循环和JSON解析填充我的数据库。当我不尝试for循环,而只是对单个对象执行时,它就工作了。这是我的密码: for i in 0..searchArray.size-1 #0..iTunesParsed['results'].size-1 // it is likely that searching for more than one item may not be benificial to us # NOTE: Need
for i in 0..searchArray.size-1 #0..iTunesParsed['results'].size-1 // it is likely that searching for more than one item may not be benificial to us
# NOTE: Need to make sure to only search for artists, filter only songs
if !(ary.include? searchArray[i])
ary.push(searchArray[i])
# grabs artist name if not in database and adds it
# NOTE: this is occuring after the check for if elements are in the
# database, change it so this occurs first
if !(Artist.exists?(artist_name: ary[i]))
# replace all spaces with '+' so it may be passed to spotify
searchResult = searchArray[i]
if searchResult.match(/\s/)
searchResult.gsub!(/\s/,'+')
end
# grabbing the artist art from the Spotify api
# NOTE: have to fix 'special characters'
spotifyUrl = "https://api.spotify.com/v1/search?q=" + searchResult + "&type=artist"
spotifyUri = URI(spotifyUrl)
spotifyResponse = Net::HTTP.get(spotifyUri)
spotifyParsed = JSON.parse(spotifyResponse)
# When putting item into the database, replace '+' with a space
searchResult.gsub!('+',' ')
# create database entry
artist = Artist.create(:artist_name =>
searchResult, :artist_info=> nil,
:biography => nil, :recent_albums => nil, :rating => nil,
:related_artists => nil, :artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url'])
end
end
问题主要在于:
artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url'])
我不知道发生了什么事。如果有人能给我指引正确的方向,那会很有帮助。我相信可能会有没有图像的艺术家。使用Rails来处理这些情况。而不是:
:artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url']
做:
或使用内联救援器:
:artist_art => (spotifyParsed['artists']['items'][0]['images'][0]['url'] rescue nil)
我相信可能有艺术家没有图像。使用Rails来处理这些情况。而不是:
:artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url']
做:
或使用内联救援器:
:artist_art => (spotifyParsed['artists']['items'][0]['images'][0]['url'] rescue nil)
看起来您正试图访问一个不存在的元素。在你创建数据库条目并查看其内容之前,试着打印出你的
spotifyParsed
。嗯,这很奇怪,当我尝试两次解析它时,“项”变为空。知道为什么会这样吗?很可能Spotify的结果不包含“条目”。顺便说一句,为了使代码更“红宝石化”,你可以考虑使用<代码>。语法而不是范围内的i
@QQPrinti请添加整个堆栈跟踪,以帮助我们确定错误所在。您可能正在从spotifyParsed数组访问无效/不存在的索引。看起来您正在尝试访问不存在的元素。在你创建数据库条目并查看其内容之前,试着打印出你的spotifyParsed
。嗯,这很奇怪,当我尝试两次解析它时,“项”变为空。知道为什么会这样吗?很可能Spotify的结果不包含“条目”。顺便说一句,为了使代码更“Ruby”,你可以考虑使用<代码>。在{Reals中,我为{i } < /Cord>语法而不是<代码>。@ QQPrinti请添加整个堆栈跟踪,以便帮助我们确定错误所在。您可能从SpistyPyPrPARD数组访问无效/不存在的索引。