Created
June 1, 2012 20:59
-
-
Save seabre/2855112 to your computer and use it in GitHub Desktop.
Import CSV Into Rails Application via ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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