Skip to main content

CSV Import: Whitespace (blank) results in an error

General • Asked by Sascha M.

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


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


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.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.