Rake Task to Import CSV Files in Rails 5.1
You can run the command:
rails g task my_namespace my_task1 my_task2
This will create lib/tasks/my_namespace.rake file. Let's create a Rake task to import prospects from a CSV file.
$ rails g task import prospect create lib/tasks/import.rake
namespace :import do desc "TODO" task prospect: :environment do end end
We can now import records from CSV:
namespace :import do desc "Import prospects from CSV file" task prospect: :environment do CSV.foreach('../3000-prospects.csv', headers: true) do |row| Prospect.create(row.to_h) end end end
This gave an error:
Errno::ENOENT: No such file or directory @ rb_sysopen - ../3000-prospects.csv
Because the rake task looks for the file from where the process is run not in relation to where the rake task is in the file system. Change the file location:
The CSV file header names must match the table column names, otherwise, you will get the error:
ActiveModel::UnknownAttributeError: unknown attribute 'First Name' for Prospect.
I had to modify the header as:
We can now run the Rake task from the root of the project.
This imported 3000 records into the database in less than a minute.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview