Import Records from CSV and Excel in Rails 5

We will continue working on the project we created in Exporting Records in CSV and Excel Formats in Rails 5. Add:

gem 'roo'

to Gemfile and run bundle. In products/index.html.erb, add file upload field:

<h2>Import Products</h2>
<%= form_tag import_products_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

Define route to import data from the uploaded file.

resources :products do
  collection do
    post :import

This defines the following route.

import_products POST   /products/import(.:format)   products#import

Implement import action in products controller.

def import

  redirect_to root_url, notice: 'Products imported.'

This gives the error:

uninitialized constant Roo::Csv





In product model, change:

spreadsheet =

We get the error, ActiveRecord::NotFound exception. Change the import line that finds a record like this:

product = find_by(id: row["id"]) || new

The entire method now looks like this:

def self.import(file)
  spreadsheet =
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    product = find_by(id: row["id"]) || new
    product.attributes = row.to_hash!

Make sure to name the headers have the same value as the column name in the database, so the header should be id, name and released_on. Delete this:

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then, nil, :ignore)
  when ".xls" then, nil, :ignore)
  when ".xlsx" then, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"

This uses Roo Gem version 2.4.0. The railscast uses Roo gem 1.10.1. You can download the code for this article from exp.

Related Articles

Watch this Article as Screencast

You can watch this as a screencast Import Records from CSV and Excel in Rails 5

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

No spam ever. Unsubscribe anytime.