Reputation: 121
Am try trying to import a tabbed file and am using Ruby CSV. The trouble is the values added to the database are returning nil and I can't figure out why.
Here's my method:
require 'csv'
desc "Import GB.full from csv file"
task :import => [:environment] do
file = "codes.csv"
CSV.foreach(file, :col_sep => "\t") do |row|
Place.create {
country_code = row[0],
postal_code = row[1],
place_name = row[2],
admin_name_1 = row[3],
admin_code_1 = row[4],
admin_name_2 = row[5],
admin_code_2 = row[6],
admin_name_3 = row[7],
admin_code_3 = row[8],
latitude = row[9],
longitude = row[10],
accuracy = row[11]
}
puts row[0]
end
end
Here's a snippet of my model entry from Rails console:
irb(main):030:0> Place.all
Place Load (3.8ms) SELECT "places".* FROM "places"
=> #<ActiveRecord::Relation [#<Place id: 1, country_code: nil, postal_code: nil, place_name: nil, admin_name_1: nil, admin_code_1: nil, admin_name_2: nil, admin_code_2: nil, admin_name_3: nil, admin_code_3: nil, latitude: nil, longitude: nil, accuracy: nil, created_at: "2016-01-23 18:10:40", updated_at: "2016-01-23 18:10:40">, #<Place id: 2, country_code: nil, postal_code: nil, place_name: nil, admin_name_1: nil, admin_code_1: nil, admin_name_2: nil, admin_code_2: nil, admin_name_3: nil, admin_code_3: nil, latitude: nil, longitude: nil, accuracy: nil, created_at: "2016-01-23 18:10:40", updated_at: "2016-01-23 18:10:40">, #<Place id: 3, country_code: nil, postal_code: nil, place_name: nil, admin_name_1: nil, admin_code_1: nil, admin_name_2: nil, admin_code_2: nil, admin_name_3: nil, admin_code_3: nil, latitude: nil, longitude: nil, accuracy: nil, created_at: "2016-01-23 18:10:40", updated_at: "2016-01-23 18:10:40">, #<Place id: 4, country_code: nil, postal_code: nil, place_name: nil, admin_name_1: nil, admin_code_1: nil, admin_name_2: nil, admin_code_2: nil, admin_name_3: nil, admin_code_3: nil, latitude: nil, longitude: nil, accuracy: nil, created_at: "2016-01-23 18:10:40", updated_at: "2016-01-23 18:10:40">
Thanks in advance!
Upvotes: 0
Views: 110
Reputation: 1023
Problem in this line
Place.create {...}
This line is interpetended by Ruby as calling method create
of class Place
with block. If you want to pass the hash as an argument to method create
it should be written as
Place.create({country_code: row[0]...})
If you want to use block syntax, then you have to pass an yielded object and setup attributes on this object like this:
Place.create { |place| place.country_code = row[0] ...}
See docs for more info.
Upvotes: 2