2016-04-05 4 views
1

forループとJSON解析を使用してデータベースを生成しようとしています。私がforループを試みていないときに、ただ一つのオブジェクトに対してそれを行うと、それは機能します。私は何が起こっているか見当がつかないRuby:forループの[未定義メソッド `[] 'for Nil:NilClass"

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

  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 

問題は主にここにある:ここに私のコードです。誰かが私を正しい方向に導くことができれば、それは多くの助けになります。

+0

を。 '#create database entry'の直前にあなたの' spotifyParsed'を表示し、その内容を見てください。 – Uzbekjon

+0

うーん、これは奇妙です、私はそれを2回解析しようとすると、 'items'は空になります。なぜこれがどんなアイデアですか? – QQPrinti

+0

ほとんどの場合、Spotifyの結果には「アイテム」が含まれていません。ところで、あなたのコードをもっと "ルビー・アイ"にするためには、 'for i in range'の代わりに' .each {} '構文を使うことを検討してください。 – Uzbekjon

答えて

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) 
関連する問題