如何将散列保存到 Sequel 数据库?

How to save a hash to a Sequel DB?

在我的种子目录中有两个文件: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>'

如何将此散列保存到我的数据库中而不出错?任何帮助都会很棒!谢谢!

看起来 Town class 在 seeds.rb 为 运行 时根本没有加载。

如果@SergioTulentsev 的评论无效,你可以 post 你的种子文件吗?特别是发生错误的第 36 行?

我猜你在行 36 上引用了 Town class,它没有加载(或类似的东西),导致:

uninitialized constant Town (NameError)