comma-csv / comma

Comma is a small CSV (ie. comma separated values) generation extension for Ruby objects, that lets you seamlessly define a CSV output format via a small DSL

Home Page:https://github.com/comma-csv/comma

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CSV::MalformedCSVError

rajkiran opened this issue · comments

Hi, i am able to import 1000s of records through CSV. I am having fields like email, name, address...
In csv file we will enter address as:
tom@gmail.com,Tom Cruise,"2-3-44, New York, USA"
If we miss closing quotation as:
"2-3-44, New York, USA #without closing quotations

I am getting the error as:

CSV::MalformedCSVError in Administration::CollegeController#import_csv
Illegal quoting in line 2.

I want an flash error message instead of error page.

Here is my controller code:

def import_csv
if params[:file].blank?
flash[:error] = "Select a CSV file to upload data."
redirect_to :back
elsif params[:file].original_filename.split('.').last != "csv"
flash[:error] = "Please upload valid csv file."
redirect_to :back
else
n = not_valid = 0
col2 = []
errors = ""
CSV.foreach(params[:file].tempfile) do |row|
if n == 0
n += 1
next
end
col1 = import_from_csv(row)
unless col1.valid?
not_valid += 1
col1.errors.full_messages.each{|m| errors << " At Line : #{n+1}
#{m}
" }
end
col2 << col1
n += 1
end
unless not_valid >= 1
col2.each(&:save)
redirect_to administration_college_users_path,:notice => "#{n-1} fields imported successfully"
else
@errors = "Errors:
#{errors}"
render :load_csv
end
end
end
private
def import_from_csv(row)
College.new( :contact_email => row[0],:name => row[1], :address=>row[2])
end

Please try to help me out..

Thanks,
Raj

Why not capture the error by using a begin / rescue block?

   begin
      ...#Controller logic
   rescue CSV::MalformedCSVError => e
       ...Error captured into 'e'
   end

Yep, i did the same but when i give rescue CSV::MalformedCSVError => e, i am getting error. So, i used the following code in the last line, before the end of CSV.foreach statement

rescue CSV::MalformedCSVError
redirect_to administration_institute_users_path,:notice => "error at line #{n+1}, Quotation marks might be improper"

ANy how thanks a lot for your response..

Hi @rajkiran, you will need to wrap the entire method, so any initialisation of the CSV should be wrapped. Then its up to you how to handle the rescue.