I am trying to make a custom rake task which searches an artist by name using Itunes API and if it exists it will store the data to a database.
I need 2 things: 1) check if an artist exists (how can I check the respone) and 2) create it with ActiveRecord if it exists.
I don't know how I can implement that, here's how my code looks so far. Thanks in advance.
require 'net/http'
require 'json'
task :artist,[""] do |t, args|
request = ITunesSearchAPI.search(:term => "#{args}")
puts request
end
Firstly, don't use the word request, it's a reserved word and could cause you problems. You might try result
instead.
If there is nothing found, you'll get an empty array back.
So you'll just need to check for
result.empty?
The search is pretty straight forward if it's based on artist name
unless Artist.exists?(name: result[0]["artistName"])
Artist.create(name: result[0]["artistName", itunes_id: result[0]["artistId"])
end
Because Apple uses a matching algorithm, it's always possible your result set can return more than one entry, I would double check that it's the one you want first.