Skip to content

Instantly share code, notes, and snippets.

@tosik
Created November 8, 2012 08:45
Show Gist options
  • Save tosik/4037612 to your computer and use it in GitHub Desktop.
Save tosik/4037612 to your computer and use it in GitHub Desktop.
CSVがステキに見える!
params[:upload_file].tap do |upload_file|
file = upload_file.tempfile.tap
master_class = upload_file.original_filename.sub('.csv', '').classify
master_class.delete_all
csv = CSV.parse(file.read, headers: true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
row.delete(nil)
if row[:id]
master_class.new(row).tap {|record|
record.id = row[:id]
}.save!
end
end
end
require 'csv'
csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
Moulding.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