Ask A Question

Notifications

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:
category,product,producttype,brand,price
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)
if warehouse.save
@imported_count += 1
else
errors.add :base, "Line #{$.} - #{warehouse.errors.full_messages.join(",")}"
end
end
end

def save
process!
errors.none?
end
end

Reply

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.

Reply

Hi Chris,

I have this in my controller:

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

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. :/

Reply

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.

Reply
Join the discussion
Create an account Log in

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

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

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