且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails CSV导入,添加到相关表

更新时间:2023-11-30 23:46:28

您可以在将常规数据添加到模型后添加一个简单的循环,并使用<方法追加到年协会。

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.