我正在尝试使用Ruby on Rails将CSV文件导入我的mongodb
。
我知道如何从shell /终端执行此操作,但不知道如何从Rails
答案 0 :(得分:1)
以本教程为例Using MongoDB to store and retrieve CSV files content in Ruby,您可以将所有值存储为字符串,因此您只需要读取CSV文件,MongoDB动态创建应该代表每个文件行的对象中的所有必需属性。给定的CSV文件:
class StoredCSV
include Mongoid::Document
include Mongoid::Timestamps
def self.import!(file_path)
columns = []
instances = []
CSV.foreach(file_path) do |row|
if columns.empty?
# We dont want attributes with whitespaces
columns = row.collect { |c| c.downcase.gsub(' ', '_') }
next
end
instances << create!(build_attributes(row, columns))
end
instances
end
private
def self.build_attributes(row, columns)
attrs = {}
columns.each_with_index do |column, index|
attrs[column] = row[index]
end
attrs
end
end
<强>用法强>
StoredCSV.import!('data.csv')
stored_data = StoredCSV.all