如何在Ruby on Rails中的数据表中读取.txt文件

时间:2017-03-10 12:58:30

标签: ruby-on-rails datatable readfile

我是rails的新手,我想读取.txt文件并将其保存到如下所示的数据库中:

ThomasLinde2 ; PeterParker2;Montagmorgen;        1.00
JulkoAndrovic3 ; KeludowigFrau1;Montagmorgen;        1.00
JohannesWoellenstein4 ; SiegmundoKrugmando3;Montagmittag;        1.00
LenaLobenswert8 ; KlausGause4;Montagmittag;        1.00

现在我想把这个.txt文件读到我的数据表中。我的代码看起来像这样:

  def read_optimization_results

if (File.exist?("Zuordnung_x.txt"))

fi=File.open("Zuordnung_x.txt", "r")
fi.each { |line|
  sa=line.split(";")
  sa0=sa[0].delete "\n"
  sa1=sa[1].delete "\n"
  sa2=sa[2].delete "\n"

  solution = Solution.find_by_period(sa2)
  solution.request = sa0
  solution.offer = sa1
  solution.period = sa2
  solution.save
}
fi.close
else
  flash.now[:not_available] = "Die Lösung wurde noch nicht berechnet!"
end
@solutions = Solution.all
render :template => "solutions/index"

end

相关数据表包括:

  create_table "solutions", force: :cascade do |t|
t.string   "request"
t.string   "offer"
t.string   "period"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

如果我read_optimization_results我总是得到no method error: undefined method 'reqeust'任何想法?

1 个答案:

答案 0 :(得分:1)

我会在这里找CSV。你基本上拥有的是由分号分隔的价值。

CSV.foreach("path/to/file.csv") do |row|
  # use row here...
end

而不是value.delete "\n"我建议您使用value.stripdocs)删除值周围的空格和换行符。

关于Solution,您缺少唯一标识符。如果你做Solution.find_by_period(...),你总是只能拥有一个period的实例,并且事先就会存在。

我想你想要创建一个新的Solution。这将通过Solution.create! request: column[0], offer: column[1], period: column[2]

完成