Search code examples
rubydatabasecsvhashsequel

How to save a hash to a Sequel DB?


In my seed directory I have two files: a seed.rb and a file.csv. I parsed and cleaned up the CSV file. Then I selected the information I wanted (lines 1, 2, 3, etc) and put that into a hash:

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

I would like to save this data (that is currently in a hash) into my Sequel database under the model I have made called town.rb. Within my model, all I have written is:

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

Note: within my migration that is associated with this model I have this written:

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

So now back in my seed.rb file, I have this following my code written to try and accomplish saving the data into my seed file:

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

However, I keep getting an error saying:

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>'

How can I save this hash to my DB without getting an error? Any help would amazing! Thanks!


Solution

  • It looks like the Town class simply isn't loaded at the point when seeds.rb is running.

    If the comment from @SergioTulentsev didn't work, can you post your seeds file? Especially line 36 where the error is occurring?

    I'm guessing that on line 36 you reference the Town class, which isn't loaded (or something along those lines), resulting in:

    uninitialized constant Town (NameError)