【发布时间】:2016-03-12 17:47:01
【问题描述】:
我想将 txt 文件中的数据导入 Ruby 中的数据库。我试图创建一个 rake 任务来做到这一点,并努力寻找一种优雅的方式。
到目前为止我的 Rake 任务:
desc "Import schools."
task :import_schools => :environment do
File.open(File.join(Rails.root, "imports", "schools.txt"), "r").each do |line|
if ! line.valid_encoding?
s = line.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
s.gsub(/dr/i,'med')
description, time, standards, books, choices = s.strip.split("\t")
u = ImportResult.new(:description => description, :time => time)
u.save
end
end
end
我的txt文件数据如下:
primary 23484775884 standard:fifth book:science choice:maths name:Joseph city:London
secondary 46537728836 standard:fourth book:english choice:maths name:Jain city:Manchester
.........
我想将这些记录中的每一个插入ImportResult 数据库并忽略每条记录的name 和city。
预期结果
ImportResult Table:
id: 1
description: primary
time: 23484775884
standard: fifth
bookname: science
谢谢
【问题讨论】:
-
您似乎有几个问题。你能把它缩小到一个吗?
-
谢谢。我编辑了我的问题,希望这有助于理解。 @乔丹
-
文本文件中的每一行是否总是以相同的顺序具有相同的字段?
-
是的@jordan 它总是以相同的顺序具有相同的字段。但是有一些
key:value对类型。谢谢
标签: ruby ruby-on-rails-3 rake