Rails CSV导入,添加到相关表 [英] Rails CSV import, adding to a related table
问题描述
我的应用程序上有一个csv导入系统(仅在本地使用),它逐行解析csv文件,并将数据添加到数据库表。这是基于教程此处。
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
在课程控制器和工作良好。有一个关系,HABTM课程和HABTM课程。在csv文件中(有效地在row [5]到row [8])是year_id。有一种方法,我可以在上面的方法中添加这个。我对如何循环4个项目并将它们添加到courses_years表格感到困惑。
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.
谢谢
Jack
Thank you Jack
推荐答案
您可以在将常规数据添加到模型后添加一个简单的循环,并使用<方法追加到年协会。
You can do this by adding a simple loop after your "normal" data is added to the model, and using the << method to append to the years association.
...
course.value = row[3]
course.pass_mark = row[4]
5.upto(8).each do |i|
one_year = Year.find(row[i])
course.years << one_year if one_year
end
if course.save
n = n+1
...
如果要确保值有效,可以在循环中添加更多检查,和/或以其他方式更改查找以查找年份。另一种方式,当相关数据是尾随结束像这样是继续添加,直到没有什么可以添加,并且还添加年份本身,如果他们还不存在:
You can add more checks in the loop if you want to make sure that the values are valid, and/or change the find to locate your year in another way. Another way when the related data is "trailing off the end" like this is to keep adding until there is nothing left to add, and also to add the years themselves if they don't exist yet:
...
course.value = row[3]
course.pass_mark = row[4]
row[5..-1].each do |year_id|
one_year = Year.find_or_create_by_id(year_id)
course.years << one_year
end
if course.save
n = n+1
...
有很多不同的方法来做到这一点,正确的方式是真正依赖于你的实际数据,但这是基本的方法。
There are a lot of different ways to do this, and the way which is right is really dependent on your actual data, but this is the basic method.
这篇关于Rails CSV导入,添加到相关表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!