Abhradip Abhradip - 5 months ago 29
Ruby Question

Struggling while trying to import a csv file in a rail application

I am going to create an rail application to import a csv file and showing its content in webpage. Everything is working fine except one thing. If the csv file contains quoted strings such as "", ",'' then the program is not working.

My app/models/user.rb file is :-

class User < ActiveRecord::Base
require 'csv'

def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
User.create! row.to_hash
end
end
end

Answer

you can create a rescue for this error use code like this - may be it works for you!

def self.import(file)
  quote_chars = %w(" | ~ ^ & *)
 begin
   CSV.foreach(csv_file, headers: :first_row, quote_char:   quote_chars.shift) do |row|
    User.create! row.to_hash
 end

 rescue CSV::MalformedCSVError
   quote_chars.empty? ? raise : retry 
 end
end
Comments