Rails import CSV, add to the appropriate table

I have a csv import system in my application (used only locally) that parses the csv file line by line and adds data to the database table. It is based on a textbook 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

It's all in the course controller and works great. There are relationships that take HABTM years and HABTM years courses. In the csv file (effective in line [5] for line [8]) - year_id. Is there a way that I can add to the method above. I am confused about how to iterate over 4 elements and add them to the classes_years table.

Thank. Jack

+3
source share
2 answers

, "" < .

...
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
...

, , / , -. , " ", , , , , , :

...
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
...

, , .

+2

, :

course.years.push(row[5])
course.years.push(row[6])
course.years.push(row[7])
course.years.push(row[8])

course.years = [ row[5], row[6], row[7], row[8] ]

. course_years.

, , -, , id , :

  .....
  year_array = Year.find(row[5], row[6], row[7], row[8])
  course.years << year_array
  .....

, , . .

+1

Source: https://habr.com/ru/post/1745278/


All Articles