我正在尝试使用mongoid创建数据库,但无法找到create方法。我正在尝试基于csv文件创建2个数据库:
extract_data类:
class ExtractData
include Mongoid::Document
include Mongoid::Timestamps
def self.create_all_databases
@cbsa2msa = DbForCsv.import!('./share/private/csv/cbsa_to_msa.csv')
@zip2cbsa = DbForCsv.import!('./share/private/csv/zip_to_cbsa.csv')
end
def self.show_all_database
ap @cbsa2msa.all.to_a
ap @zip2cbsa.all.to_a
end
end
课程DbForCSV的工作原理如下:
class DbForCsv
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
def self.import!(file_path)
columns = []
instances = []
CSV.foreach(file_path, encoding: 'iso-8859-1:UTF-8') 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
ap attrs
attrs
end
end
我不知道所有领域,它可能会及时改变。这就是我创建数据库和通用mehtods的原因。
修复'create!'后我还有另一个问题。问题。
我正在使用编码来确保只处理UTF8字符,但我仍然看到:
{
"zip" => "71964",
"cbsa" => "31680",
"res_ratio" => "0.086511098",
"bus_ratio" => "0.012048193",
"oth_ratio" => "0.000000000",
"tot_ratio" => "0.082435345"
}
在代码中执行'ap attrs'时。如何确保'zip' - &gt; '拉链'
由于
答案 0 :(得分:1)
create!
是一个类方法,但您尝试将其称为实例方法。你的import!
方法也不应该是一个实例方法,它应该是一个类方法,因为它会生成你的类的实例:
def self.import!(file_path)
#-^^^^
# everything else would be the same...
end
你也可以使build_attributes
成为一个类方法,因为它只是另一个类方法的辅助方法:
def self.build_attributes
#...
end
然后,在使用new
时,您不需要那个奇怪的import!
来电:
def self.create_all_databases
@cbsa2msa = DbForCsv.import!('./share/private/csv/cbsa_to_msa.csv')
@zip2cbsa = DbForCsv.import!('./share/private/csv/zip_to_cbsa.csv')
end