Created
October 6, 2011 10:52
-
-
Save naoty/1267124 to your computer and use it in GitHub Desktop.
seeds file which inserts csv data in a specific directory into mongodb
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
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