模型已填充,但在CSV导入后值为nil

时间:2016-01-23 18:46:41

标签: ruby-on-rails ruby csv

我尝试导入选项卡式文件并使用Ruby CSV。麻烦的是添加到数据库的值返回nil,我无法弄清楚原因。

这是我的方法:

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

以下是Rails控制台中我的模型条目片段:

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

这一行的问题

Place.create {...}

这一行由Ruby作为类create的调用方法Place进行交互。如果要将哈希作为参数传递给方法create,则应将其写为

Place.create({country_code: row[0]...})

如果你想使用块语法,那么你必须在这个对象上传递一个屈服对象和设置属性,如下所示:

Place.create { |place| place.country_code = row[0] ...}

有关详细信息,请参阅docs