Reef Rashid
Reef Rashid

Reputation: 59

Mapping csv columns to model?

I'm creating a database of students and have the following code to read a csv file with headers and store each of the non-header lines as a student object.

class Student < ApplicationRecord
     def self.import(file)
          CSV.foreach(file.path, headers: true) do |row|
                Student.create! row.to_hash
          end
     end
end 

My issue is that the csv files I need to import can be of different formats. Some might have headers organized like:

Undegraduate Major | First Name | Last Name | Class Year | Undergraduate Minor

First_name | Last_name | Major | Minor

First_name | Last_name | Class_year

As you can see, not all of the fields might be present, and they definitely might not be in the same order. How can I deal with this?

Upvotes: 0

Views: 1827

Answers (1)

Leantraxxx
Leantraxxx

Reputation: 4606

You can do something like this to map the columns with attributes:

MAP = {
  "Undegraduate Major" => :major,
  "First Name" => :first_name,
  "Last Name" => :last_name,
  "Class Year" => :class_year,
  "Undergraduate Minor" => :minor,
  "Major" => :major,
  "Minor" => :minor,
  "Class_year" => :class_year
}

CSV.foreach(file.path, headers: true) do |row|
  data = {}

  row.to_hash.each do |k, v|
    key = MAP[k]
    data[key] = v
  end

  Student.create! data
end

Upvotes: 2

Related Questions