如何将哈希保存到续集数据库?

时间:2015-04-28 12:30:50

标签: ruby database csv hash sequel

在我的种子目录中,我有两个文件:seed.rbfile.csv。我解析并清理了CSV文件。然后我选择了我想要的信息(第1,2,3行等)并将其放入哈希:

require 'csv'
data = {}
CSV.foreach("file.csv") do |line|
  data[line[1]] = {:address => line[2].to_s, :city => line[3].to_s, :state => line[4].to_s, :zipcode => line[5].to_s, :phone => line[6].to_s}
end

我想将这些数据(当前是哈希)保存到我的Sequel数据库中,名为town.rb。在我的模型中,我所写的是:

class Town < Sequel::Model
   #put conditions here
end

注意:在与此模型关联的迁移中,我写了:

Sequel.migration do
  up do
    create_table(:towns) do
      primary_key :__id__

      String :name, :null => false
      String :address
      String :city
      String :state
      String :zipcode
      String :phone

    end
  end

  down do
    drop_table(:towns)
  end
end

现在回到我的seed.rb文件中,我按照我的代码编写,尝试将数据保存到种子文件中:

data do |key, record|
  c = Town.new #LINE 36
  c.name = key
  c.address = record[:address]
  c.city = record[:city]
  c.state = record[:state]
  c.zipcode = record[:zipcode]
  c.phone = record[:phone]
  c.save
end

但是,我一直收到错误说:

seed.rb:36:in `block in <top (required)>': uninitialized constant Town (NameError)
    seed.rb:35:in `each'
    seed.rb:35:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

如何在不收到错误的情况下将此哈希保存到我的数据库?任何帮助都会惊人!谢谢!

1 个答案:

答案 0 :(得分:1)

看起来Town类在seeds.rb运行时没有加载。

如果来自@SergioTulentsev的评论不起作用,您可以发布您的种子文件吗?特别是发生错误的行36

我猜你在36行上引用了Town类,它没有被加载(或者那些行中的某些内容),导致:

uninitialized constant Town (NameError)
相关问题