Tuesday, July 9, 2013

Uploading CSV files to a Rails Application using ActiveAdmin

Recently I had try and upload CSV files to a rails application via Active Admin. I had the inkling that maybe I was not the first to have done this. A short google search later and I was lead to this answer on Stack Overflow

I loved it except for the processing class listed under csv_db. It seemed too limiting in that it requires EVERY column to be there whether data is present or not. I recalled a Railscast that offered up a much more flexible solution and created this:

require 'csv'
class CsvDb
  class << self
    def convert_save(model_name, csv_data)
      begin
        target_model = model_name.classify.constantize
        CSV.foreach(csv_data.path, :headers => true) do |row|
          target_model.create(row.to_hash)
        end
      rescue Exception => e
        Rails.logger.error e.message
        Rails.logger.error e.backtrace.join("\n")
      end
    end
  end
end


If you replace the code from the Stackoverflow post in csv_db with this you should be able to load any number of columns you wish. As soon as I figure out the updating of existing records I will post a follow-up.