将json保存到模型和db

时间:2016-04-14 16:15:48

标签: ruby-on-rails ruby json rake rake-task

我正在尝试制作一个自定义rake任务,使用Itunes API按名称搜索艺术家,如果存在,它会将数据存储到数据库中。

我需要两件事:1)检查艺术家是否存在(如何检查响应)和2)使用ActiveRecord创建它(如果存在)。

我不知道如何实现这一点,这就是我的代码到目前为止的样子。 提前谢谢。

require 'net/http'
require 'json'

  task :artist,[""] do |t, args|
    request = ITunesSearchAPI.search(:term => "#{args}")
    puts request
  end

2 个答案:

答案 0 :(得分:0)

首先,不要使用单词request,它是一个保留字,可能会导致问题。您可以尝试使用result

如果找不到任何内容,您将获得一个空数组。

所以你只需要检查

result.empty?

如果基于艺术家名称

,则搜索非常简单
unless Artist.exists?(name: result[0]["artistName"])
  Artist.create(name: result[0]["artistName", itunes_id: result[0]["artistId"])
end

因为Apple使用匹配算法,所以你的结果集总是可以返回多个条目,我会仔细检查它是你想要的那个。

答案 1 :(得分:0)

  

1)检查艺术家是否存在(我如何检查反复)

request = ITunesSearchAPI.search(:term => "#{args}")
puts request

当iTunes上没有艺术家时,它将取决于请求的内容或ITunesSearchAPI.search方法的行为方式。通常,API在JSON中返回一个空数组。因此,您只需检查结果数组是否为空。

# Provided request['artists'] is an array
if request['artists'].empty?
    # no artists
else
    # there are artists
end

我们正在使用它时,您不必插入args,只需将其打印出来或使用.to_s方法,如果您想将其转换为String。< / p>

ITunesSearchAPI.search(:term => args.to_s)
  

2)使用ActiveRecord创建它(如果存在)。

您可以在没有Rails的情况下使用ActiveRecord。它一直是covered many times。它归结为安装active_record gem,包括它,建立连接并继承ActiveRecord::Base

require 'active_record'
require 'sqlite3'
require 'logger'

ActiveRecord::Base.logger = Logger.new('db.log')
ActiveRecord::Base.establish_connection(
  adapter: 'sqlite3',
  database: 'db/mydb.sqlite3',
  timeout: 5000,
  pool: 5
)

class YourModel < ActiveRecord::Base
end