Skip to content

Upload CSV to multiple tables

by admin on September 23rd, 2009

Uploading a CSV to a single table is easy enough, but what if elements of your CSV go to separate tables and needed to be primary and foreign keys for each other?

I have two tables, Categories and Items. I have a CSV that looks like this:
Category One,Item One,Item one descriptions,,
,Item two,Item two descriptione,,
,Item three,Item three description,,
,Item four,Item four description,,
Category Two,Item five,Item five description,,
,Item six,Item six description,,
,Item seven,Item seven description,,

My controller method looks like this:

require 'csv'
def csv_import
@parsed_file=CSV::Reader.parse(params[:csv][:file])
@parsed_file.each do |row|
category = row[0]
if !category.nil?
c = Category.new
c.name = row[0]
c.save
@new_cat = c.id
end


i = Item.new
i.name = row[1]
i.description = row[2]
i.category_id = @new_cat
i.save
end


redirect_to :controller => 'category', :id => params[:csv][:item]

And my form looks like this:
<% form_for :csv, :url=>{:controller=>"category", :action=>"csv_import"}, :html => { :multipart => true } do |f| -%>

Select a CSV File : <%= f.file_field :file -%> <%= submit_tag 'Submit' -%>

<% end -%>

From → Ruby on Rails

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS