Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active February 7, 2019 13:59
Show Gist options
  • Save thadeu/b40ee12ece52cb393afb9256713c340b to your computer and use it in GitHub Desktop.
Save thadeu/b40ee12ece52cb393afb9256713c340b to your computer and use it in GitHub Desktop.
Rake Import CSV with Ruby/Rails
# frozen_string_literal: true

namespace :import do
  desc 'import CSV'
  task csv: :environment do
    csv_file = File.join Rails.root, 'tmp/file.csv'
    counter = 0

    options = {
      encoding: 'windows-1250', 
      headers: true, 
      row_sep: :auto, 
      col_sep: ';', 
      skip_blanks: true
    }

    CSV.foreach(csv_file, options) do |row|
      name = row['NAME'].presence

      params = {
        name: name
      }

      save_params = Table.find_or_create_by!(params)

      if save_params.persisted?
        counter += 1
        puts "#{counter} : #{params}"
      end
    end
  end
end
rake import:csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment