Ruby:"未定义的方法`[]'为零:NilClass"在for循环中

时间:2016-04-05 03:46:25

标签: 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 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'])

我不知道发生了什么。如果有人能指引我朝着正确的方向前进,那将会有很大的帮助。

1 个答案:

答案 0 :(得分:0)

我相信艺术家可能没有图像。使用Rails'try来处理这些情况。而不是:

:artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url']

做的:

:artist_art => spotifyParsed.try(:[],'artists')
                            .try(:[], 'items')
                            .try(:first)
                            .try(:[], 'images')
                            .try(:first)
                            .try(:[], 'url')

或使用内联救援人员:

:artist_art => (spotifyParsed['artists']['items'][0]['images'][0]['url'] rescue nil)