1

I'm trying to import CSV data into an already existing Rails table.

My CSV has columns of lec_exam, location, meeting_days, begin_time, and end_time. My table looks as follows:

create_table "courses", force: true do |t|
  t.string   "lec_exam"
  t.string   "location"
  t.string   "meeting_days"
  t.time     "begin_time"
  t.time     "end_time"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "status"
end

The status (i.e. taken vs open) field is something I want to update based on the current time versus the presence of a course occurring at that time.

Every time I import the CSV data the last column (end_time) does not get properly imported because each course has an end_time of nil, when a simple glance at the CSV shows otherwise.

I have tried

CSV.foreach(file.path, headers: true) do |row|

  #course_hash = row.to_hash # exclude the price field
  #course = Course.where(id: course_hash["id"])
  row = Course.create!({
    :lec_exam => row[0],
    :location => row[1],
    :meeting_days => row[2],
    :begin_time => row[3],
    :end_time => row[4]
  }) 

as well as the to_hash method. Any help towards a solution would be great. Thanks!

Ryan
  • 414
  • 1
  • 5
  • 16

2 Answers2

0

To import a CSV data into an existing Rails table add:

require 'csv'    

csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  Moulding.create!(row.to_hash)
end

In the rake task, or in a controller action.

Source: Ruby on Rails - Import Data from a CSV file

Hope this helps!

Community
  • 1
  • 1
Kevin Austin
  • 184
  • 7
0

Solved.

Model had an unneccessary

attr_accessor:

tag. Bleh.

Ryan
  • 414
  • 1
  • 5
  • 16