Rails CSV import, adding to a related table
- by Jack
Hi,
I have a csv importing system on my app (used locally only) which parses the csv file line by line and adds the data to the database table. This is based on a tutorial here.
require 'csv'
def csv_import
@parsed_file=CSV::Reader.parse(params[:dump][:file])
n = 0
@parsed_file.each_with_index do |row, i|
next if i == 0 #ignore the first row
course = Course.new
course.title = row[0]
course.unit_code = row[1]
course.course_type = row[2]
course.value = row[3]
course.pass_mark = row[4]
if course.save
n = n+1
GC.start if n%50==0
end
flash.now[:message] = "CSV Import Successful, #{n} new courses added to the database."
end
redirect_to(courses_url)
end
This is all in the courses controller and works fine. There is a relationship that courses HABTM years and years HABTM courses. In the csv file (effectively in row[5] to row[8]) are the year_id s. Is there a way that I can add this within the method above. I am confused as to how to loop over the 4 items and add them to the courses_years table.
Thank you
Jack