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)

有帮助吗?

解决方案 2

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

其他提示

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top