【发布时间】:2016-04-18 13:47:20
【问题描述】:
这是一个搜索艺术家的 rake 任务,如果存在,它将与艺术家专辑一起存储。我尝试使用gem,但由于某种原因,gem 返回了我并不真正需要的东西。如果我搜索一个艺术家,它工作正常。
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) 如何保存所有专辑,而不仅仅是一张?
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 就是这样。
标签: ruby-on-rails ruby rake