Search code examples
ruby-on-railsrubyruby-on-rails-4rake

Rails populate db rake task OpenURI::HTTPError: 500 Internal Server Error


I am trying to make rake task to populate db from JSON API fixer.io, but when i type my rake :
rake db:populate
this error occurs:

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)

This is my rake task (populate.rake) in lib/tasks:

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

Please help me, I have no idea what causes this problem.


Solution

  • the main problem is here, you are not taking keys of "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