0

Aloha, as always, any help is greatly appreciated. I'm importing a CSV and in the headers I have all caps and colons (for example, EXT:MAT:PIDTC is one). How would I go about manipulating the headers on the way in? maybe I want to change the example above to thisHeader or something to match up with my :thisHeader attribute in my SpiritTrial model.

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

1 Answer 1

1

CSV.foreach & co. take a :header_converters option, which should be a Proc or array of Procs that take a header as an argument and return a new value for that header. Given your example, you would do something like this:

class SpiritTrial < ActiveRecord::Base
  CSV_HEADER_MAP = {
    "EXT:MAT:PIDTC" => :thisHeader,
    # ...
  }

  CSV_HEADER_CONVERTER = ->(header) { HEADER_MAP.fetch(header, header).to_sym }

  def self.import(file)
    CSV.foreach(file.path, headers: true, header_converters: CSV_HEADER_CONVERTER) do |row|
      SpiritTrial.create! row.to_hash
    end
  end
end

You can see an example sans Rails on repl.it: https://repl.it/FoAj

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.