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

This creates:

namespace :import do
  desc "TODO"
  task prospect: :environment do

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|

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.

rails import:prospect

This imported 3000 records into the database in less than a minute.


Related Articles

Create your own user feedback survey