All threads / CSV Import: Whitespace (blank) results in an error
Ask A Question


You’re not receiving notifications from this thread.

CSV Import: Whitespace (blank) results in an error

Sascha M. asked in General

Hi there,

I`m using the CSV Upload as described in one of your pro-tutorials.

The code loops through the csv and adds records to the specific table. But if there is a whitespace inside a row, the upload get's stuck.

Column head:
Shoes,Adidas Test Shoes ,Base,Adidas,43.99

Notice the blank behind "Adidas Test Shoes". This produces the error. What can be done here?

This is the import code:

class Warehouse::Import
include ActiveModel::Model
attr_accessor :file, :imported_count

def process!
@imported_count = 0
CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
warehouse = Warehouse.assign_from_row(row)
@imported_count += 1
errors.add :base, "Line #{$.} - #{warehouse.errors.full_messages.join(",")}"

def save

Hey Sascha, what's the error you're getting? Normally whitespace like that makes no difference since it's "comma separated" which means that only extra commas would cause it to mess up so I suspect there must be something else going on.

Hi Chris,

I have this in my controller:

def import
@import = warehouse_import_params
redirect_to warehouses_url, notice: "Imported #{@import.imported_count} products."
@warehouses = Warehouse.all
flash[:alert] = "There were #{@import.errors.count} errors with your CSV file."
render action: :index
redirect_to warehouses_url, notice: "No CSV :("

As it loops through until the column with the blankspace it only gives me an "No CSV" error. Strangely it is the blankspace. As soon as i deleted it everything did work fine. :/

You're using rescue without capturing the exception, so you actually lose the error that's happening. If you remove that block, you'll get the exception printed out.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 68,099+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.