Skip to content

Instantly share code, notes, and snippets.

@naoty
Created October 6, 2011 10:52
Show Gist options
  • Save naoty/1267124 to your computer and use it in GitHub Desktop.
Save naoty/1267124 to your computer and use it in GitHub Desktop.
seeds file which inserts csv data in a specific directory into mongodb
require 'csv'
require 'mongo'
path = "#{Rails.root}/db/seeds/"
db = Mongo::Connection.new.db('database_name')
Dir.open(path).each do |f|
if f.match(/(.*)\.csv$/)
col = db.collection($1)
col.remove
CSV.foreach("#{path}#{$1}.csv", headers: true, header_converters: :symbol) do |row|
fields = row.fields.map{|item| item.match(/^\d*$/) ? item.to_i : item }
col.insert(Hash[*[row.headers, fields].transpose.flatten])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment