Rails填充db rake任务OpenURI :: HTTPError:500内部服务器错误

时间:2016-01-20 19:51:04

标签: ruby-on-rails ruby ruby-on-rails-4 rake

我正在尝试使用rake任务从JSON API fixer.io填充数据库, 但是当我输入我的耙子时:
rake db:填充
发生此错误:

OpenURI::HTTPError: 500 Internal Server Error
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:16:in `block (5 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:13:in `block (4 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `block (3 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:populate
(See full trace by running task with --trace)

这是我在lib / tasks中的rake任务(populate.rake):

require 'open-uri'

namespace :db do
  desc "Erase and fill database"
  task :populate => :environment do
    require 'populator'

    [ConversionRate].each(&:delete_all)
    n = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys.count
    currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
    currencies.each do |curr1|
      currencies.each do |curr2|
        ConversionRate.populate 1 do |cr|
          cr.currency1 = curr1
          cr.currency2 = curr2
          cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
      end
    end
  end
  end
end

请帮助我,我不知道是什么导致了这个问题。

1 个答案:

答案 0 :(得分:1)

主要问题在于,您没有使用"rates"

currencies = JSON.load(open('http://api.fixer.io/latest')).keys

currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
require 'open-uri'

namespace :db do
  desc "Erase and fill database"
  task :populate => :environment do
    require 'populator'

    [ConversionRate].each(&:delete_all)

    latest_data = JSON.load(open('http://api.fixer.io/latest'))

    currencies = latest_data["rates"].keys
    n = currencies.count

    currencies.each do |curr1|
      currencies.each do |curr2|
        ConversionRate.populate 1 do |cr|
          #take care of any error, as we are going to call third party api here
          begin
            cr.currency1 = curr1
            cr.currency2 = curr2
            cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
          rescue => e
            puts "error #{e}"
          end
        end
      end
      #give a bit rest
      sleep 2
    end
  end
end