1

As per this example, the following method:

require "csv"

def import_vault_data(filename)    
    fn = "#{RAILS_ROOT}/public/data/#{filename}"
    CSV.foreach(fn, :headers => true) do |row|
        House.create!(row.to_hash)    
    end
end

is producing this error:

undefined method `to_hash' for #<Array:0x104cc07b8>

Any clue as to what is missing?

I am using rails 2.3.9

Community
  • 1
  • 1
iamtoc
  • 1,569
  • 4
  • 17
  • 24

3 Answers3

6

May be a bit late for the answer but you need to:

CSV.foreach(file.path, headers: true) do |row|

as you cant call to_hash unless you have headers in the hash

Rhys
  • 429
  • 2
  • 5
  • 12
2

try this for ruby 1.8.7

House.create!(row.hash)   
Dipak Panchal
  • 5,996
  • 4
  • 32
  • 68
  • This solved the hash error. Brilliant! It effectively created a a new 'House' record, but all fields were null. I have made sure that fields in the csv are the same name and in the same order as the 'houses' database table. I'm guessing there's some other requirement I'm missing. Moreover, it only created 1 record with null fields. There are 50 records in the csv. – iamtoc Oct 06 '12 at 05:36
  • I set a breakpoint on 'row'. Based on the cell values being returned, it appears as though it doesn't know that the first row are header names. Do I need to specify a certain field delimiter when generating the csv? Or perhaps tell the hash command to use first row as headers? If so how would I do this. I'm guessing out loud. – iamtoc Oct 06 '12 at 05:54
  • I tried this: csv = CSV.parse(fn, :headers => true) csv.each do |row| row = Hash[row].with_indifferent_access House.create!(Hash[row].symbolize_keys) end -- It produced the correct number of records in the database, but still all database fields are null. – iamtoc Oct 06 '12 at 05:59
2

you can also do

House.create!(Hash[row])
saihgala
  • 5,724
  • 3
  • 34
  • 31
  • I tried this as well. Worked like a charm! Created database records, but all database fields were null. – iamtoc Oct 06 '12 at 06:04