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

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now