0

I am using Roo to parse my CSV files for import. Everything works perfectly, but sometimes the end users will change the column headers of the excel file. For example, if the db column is first_name the users might change the header in the excel file to firstname. In such a casse, it is easy to use alias_attribute method to map a header to the correct db column name.

However, how can I handle a situation where the column header in the excel is very long? For example, something like the user's first name and last name The alias_attribute method cannot be used here:

alias_attribute :first_name, :the user's first name and last name

How would you parse verbose or long column headers in a csv file to map to a normal db column name?

Here is my implementation of roo:

def load_imported_users
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(2)
    (3..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      user = User.find_by_national_id(row["national_id"]) || User.new

      user.attributes = row.to_hash
      user
    end
  end

Any help would be appreciated.

adamvanbart
  • 67
  • 1
  • 10
  • Why don't you just use the `string` like `alias_attribute "first_name", "the user's first and last name"`? Symbol is kind of `string` without an extra baggage anyways :) – mutantkeyboard Oct 15 '19 at 13:07
  • Really great! How would I use the same approach when mapping to associations columns? Something like ```alias_attribute "country_name", "country of origin" ``` but this time around, instead of saving the name of the country, you convert it to ```country_id``` column in the table? – adamvanbart Oct 16 '19 at 13:02

0 Answers0