0

I've searched all over this forum for solution to the above problem, but everything I tried didn't work. Basically, i have a model Library, with corresponding libraries table in my sqlite3 database. I have a csv file named libraries.csv which contains all the data I want to import into the database.

I tried the method on the second answer on this page but it's still not working. I made sure to create my rake file 'import_libraries.rake in the lib/tasks folder and I also saved the libraries.csv file in that folder but i keep getting this error message:

rake aborted!
Don't know how to build task 'import_libraries' (See full trace by running task with --trace)

This is the current code I'm using:

require 'csv'
desc "Imports a CSV file into an ActiveRecord table"
task :import, [:filename] => :environment do    
    CSV.foreach('libraries.csv', :headers => true) do |row|
      Library.create!(row.to_hash)
    end
end

But when I run bundle exec rake import_libraries, I get the error message above.

Is there anything I am doing wrong? i would appreciate your help guys. Thanks

EDIT

I renamed the rake file from import_libraries.rake to just import.rake On running bundle exec rake import, the error message i now get is:

rake aborted! invalid byte sequence in UTF-8 C:/Users/username/rails_app_name/lib/tasks/import.rake:4:in `block in ' Tasks: TOP => import (See full trace by running task with --trace)

Community
  • 1
  • 1
Shikasan
  • 331
  • 1
  • 6
  • 20

2 Answers2

1

Based on the error you're getting and the task you have defined, you should be calling:

bundle exec rake import  #=> you're currently calling import_libraries which indeed doesn't exist

With rake you call a task based on the name you give to the tasks, not on the name of the file (remember you can have many task inside each of those rake files).

fmendez
  • 7,250
  • 5
  • 36
  • 35
  • Hi fmendez. Should I in that case rename my rake file to import instead? – Shikasan Mar 13 '13 at 22:07
  • Not necessarily. You can name that file any name you want (it should be in the lib/task). You should, for the sake of clarity, give it a descriptive name. When it comes to executing a rake task what matters is that you use the name you assign to it in `task :name_you_assign_to_the_task` inside the .rake file. – fmendez Mar 13 '13 at 22:12
  • Hi. Please check out the new error message I now receive. Thanks – Shikasan Mar 13 '13 at 22:13
0

I finally solved the problem by using this code:

namespace :csv do

  desc "Import CSV Data"
  task :import => :environment do

    require 'csv'

    csv_file_path = 'lib/tasks/libraries.csv'

    CSV.foreach(csv_file_path, headers: true) do |row|
      row = Library.create!({
        :column_name1 => row[0],
        :column_name2 => row[1],
        :column_name3 => row[2],
        .
        . 
        :last_column => row[6]
      })
      puts "Success!"
    end
  end
end
Shikasan
  • 331
  • 1
  • 6
  • 20