Anu
Joined: 01 Jan 2010 Posts: 80
|
Posted: Tue Feb 16, 2010 12:07 pm Post subject: Rails CSV file import functionality |
|
|
Hi,
Import CSV file :
*It allows us to upload CSV data onto the mysql database.
Include the method csv_import method in the controller,
def csv_import
@product=CSV::Reader.parse(params[:dump][:file])
n=0
@product.each do |row|
c=Product.new
c.title=row[1]
c.description=row[2]
c.price=row[3]
if c.save
n=n+1
GC.start if n%50==0
end
flash.now[:message]="CSV Import Successful,
end
Now provide the view for the method,in rhtml file.
<% form_for :dump, :url=>{:controller=>"sample",
:action=>"csv_import"},
:html => { :multipart => true } do |f| -%>
<table">
<tr>
<td>
<label for="product">
Select a CSV File :
</label>
</td>
<td >
<%= f.file_field :file -%>
</td>
</tr>
<tr>
<td colspan='2'>
<%= submit_tag 'Submit' -%>
</td>
</tr>
</table>
<% end -%>
in the above code product is my table,and sample is the controller.
when we run this code,the browser allows you import a csv file,and when we click on submit ,the records which are exsted in the file are uploaded to the database.
Thanks & Regards,
Anasuya.N |
|