アーティストを検索するレーキタスクです。存在する場合は、アーティストのアルバムとともに保存します。私はgemを使用しようとしましたが、何らかの理由で宝石が本当に必要としないものを返します。私がアーティストを検索すると、それはうまく動作します。ActiveRecordを使用して多数のアルバムを作成する
result = ITunesSearchAPI.lookup(:id => 372976 , :entity => 'album')
これを返します。
{"wrapperType"=>"artist", "artistType"=>"Artist", "artistName"=>"ABBA", "artistLinkUrl"=>"https://itunes.apple.com/us/artist/abba/id372976?uo=4", "artistId"=>372976, "amgArtistId"=>3492, "primaryGenreName"=>"Pop", "primaryGenreId"=>14}
を私はまったく必要とするものではありませんています。 Here's私は何をすべきですか?
私はそれを自分自身でコーディングすることに決めました。そして空のモデルを保存することに気付きました。私のアルバムのすべては無しです。 2つの質問:
1)どうすれば修正できますか?
2)どうすれば1つではなくすべてのアルバムを保存できますか?
require 'net/http'
task :artist,[""] => :environment do |t, args|
result = ITunesSearchAPI.search(:term => args.to_s, :entity => 'musicArtist')
if result.empty? then puts "Nothing was found. Try another artist."
puts result
elsif result
uniqueness = Artist.find_by(itunes_id: result[0]["artistId"])
if uniqueness.nil?
Artist.create(name: result[0]["artistName"], itunes_id: result[0]["artistId"])
puts result
else
puts "The artist already exists in database"
end
end
if uniqueness.nil?
album = URI('https://itunes.apple.com/lookup')
album_params = { :id => result[0]['artistId'], :entity => 'album'}
album.query = URI.encode_www_form(album_params)
album_response = Net::HTTP.get_response(album)
puts album_response.body
Album.create!(name: album_response.body[0]["collectionName"], artwork_url_100: album_response.body[0]["artworkUrl100"])
end
end
スキーマ:
ActiveRecord::Schema.define(version: 20160418120725) do
create_table "albums", force: true do |t|
t.string "name"
t.string "artwork_url_100"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "artists", force: true do |t|
t.string "name"
t.integer "itunes_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "artists", ["itunes_id"], name: "index_artists_on_itunes_id", unique: true
end
「Album」のスキーマとモデルコードを投稿できますか? –
@AnthonyE確かに、投稿を更新しました。アルバムはbelongs_to:artist これはそれです。 – r0uder