Skip to content

Instantly share code, notes, and snippets.

@seabre
Created June 1, 2012 20:59
Show Gist options
  • Save seabre/2855112 to your computer and use it in GitHub Desktop.
Save seabre/2855112 to your computer and use it in GitHub Desktop.
Import CSV Into Rails Application via ActiveRecord
# If you are using a gem like paper_trail that records
# user edit history, you should "login" first.
# See this gist for more details if you are
# using Devise:
# https://gist.github.com/2855072
require 'csv'
csv_text = File.read('my_csv_file_to_import.csv')
# The CSV header labels should match exactly what the fields
# in your model are. They don't have to be in order, but you
# at least must have data for the required fields for the model.
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
# Certain fields like Dates should be converted from string into
# the appropriate object. With dates you can do something like this:
# row["some_date_field"] = Date.strptime(row["some_date_field"],"%m/%d/%Y")
MyModel.create!(row.to_hash.symbolize_keys)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment