How to import CSV file in rails
How to import CSV file in rails?
The CSV text-file format is a common choice for both import and export when performing data migrations. What if you want to import CSV files within a Rails application?
Here is the code that allow you to upload CSV data onto the MySQL database from the web interface
This code save data direct to database without saving it to temp file
Controller:
def csv_import
@parsed_file=CSV::Reader.parse(params[:dump][:file])
n=0
@parsed_file.each do |row|
c=CustomerInformation.new
c.job_title=row[1]
c.first_name=row[2]
c.last_name=row[3]
if c.save
n=n+1
GC.start if n%50==0
end
flash.now[:message]=”CSV Import Successful, #{n} new records added to data base”
end
View:
your view will look like
| <%= f.file_field :file -%> | |
| <%= submit_tag 'Submit' -%> | |
<% end -%>