I am trying to insert data via csv to database. This is my controller code
require 'csv' def index end def add @filename=CSV::Reader.parse(params[:dump][:file]) n=0 CSV::foreach(@filename, :headers => true) do |row| Student.new(row.to_hash.symbolize_keys).save n=n+1 end flash.now[:message]="CSV Import Successful, #{n} new records added to data base" end
Now when i am inserting a csv file i am getting the error
**can't convert CSV::IOReader into String**
My ruby version is 1.8.7
Any help will be appreciated.
If you are using Ruby, you could use the following code:
require 'csv'
def index
end
def add
n=0
CSV::foreach(params[:dump][:file]) do |row|
Student.new(row.to_hash.symbolize_keys).save
n=n+1
end
flash.now[:message]="CSV Import Successful, #{n} new records added to data base"
end
You can get more information about CSV:foreach on http://apidock.com/ruby/CSV
I failed with the above reply because I assumed that the [:dump][:file] was the path to the file (string object), but seeing that error, you should read the file first (it is a TempFile object), and then parse the content as string:
require 'csv'
def index
end
def add
n=0
CSV::parse(params[:dump][:file].read, :headers => true) do |row|
Student.new(row.to_hash.symbolize_keys).save
n=n+1
end
flash.now[:message]="CSV Import Successful, #{n} new records added to data base"
end