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:

    require 'csv'

   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

 <% form_for :dump, :url=>{:controller=>"customer_informations",
                    :action=>"csv_import"},
                    :html => { :multipart => true } do |f| -%>
 <table">
   <tr>
     <td>
      <label for="dump_file">
        Select a CSV File :
      </label>
     </td>
     <td >
       <%= f.file_field :file -%>
     </td>
   </tr>
   <tr>
     <td colspan='2'>
       <%= submit_tag 'Submit' -%>
     </td>
   </tr>
 </table>
<% end -%>

3 Comments »

  1. Nice code!!!
    Do you know any way to use this with the FasterCSV class?

  2. chester said

    specify the step by step process including the database name, table name and field names.
    i’m a newby in RoR, please.
    thanks.

  3. Bounga said

    Javier > Easy, just use :

    FasterCSV.foreach(params[:dump][:file]) do |row|

RSS feed for comments on this post · TrackBack URI

Leave a Comment