0

我正在尝试从 csv 文件中播种一个名为国家的表。其他种子按我指定的顺序工作,但这个种子按字母顺序生成一个 INSERT 语句,该语句未正确映射到 csv 文件中的字段。表国家有一个主键约束,但没有顺序或默认值。我也调用了 rake db:schema:dump,以防模式出现故障而没有运气。有任何想法吗?

模型

class Country < ActiveRecord::Base
  attr_accessible :id, :name, :abbreviation, :area, :population, :internet_users, :last_updated
end

架构.rb

create_table "countries", :id => false, :force => true do |t|
    t.integer  "id",                           :null => false
    t.string   "name",           :limit => 50, :null => false
    t.string   "abbreviation",   :limit => 5,  :null => false
    t.integer  "area"
    t.integer  "population"
    t.integer  "internet_users"
    t.datetime "last_updated"
  end

CSV 样本

1,Afghanistan,AF,"645,807","30,419,928","1,520,996",6/12/2013
2,Albania,AL,"28,748","2,986,952","1,441,928",12/11/2013
3,Algeria,DZ,"2,381,741","34,586,184","4,700,000",6/10/2013
4,American Samoa,AS,197,"67,242","3,040",3/11/2013

种子.rb

@seedfilepath = "#{Rails.root}/db/seedfiles/" 
Country.delete_all
open(@seedfilepath + "countries.csv") do |records|
  records.read.each_line do |record|
    id, name, abbreviation, area, population, internet_users, last_updated = record.chomp.split(',')
    @country = Country.create!(id: id, name: name, abbreviation: abbreviation, area: area, population: population, internet_users: internet_users, last_updated: last_updated)
  end
end

错误

$ rake db:seed
rake aborted!
PG::Error: ERROR:  value too long for type character varying(5)
: INSERT INTO "countries" ("abbreviation", "area", "id", "internet_users", "last_updated", "name", "population") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"
C:/Users/mmoore/Documents/rubyapps/visitdays/db/seeds.rb:14:in `block (2 levels) in <top (required)>'
C:/Users/mmoore/Documents/rubyapps/visitdays/db/seeds.rb:12:in `each_line'
C:/Users/mmoore/Documents/rubyapps/visitdays/db/seeds.rb:12:in `block in <top (required)>'
C:/Users/mmoore/Documents/rubyapps/visitdays/db/seeds.rb:11:in `<top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
4

2 回答 2

0

对我来说,这个问题让我的机器或 rails 实例处于非常糟糕的状态。我不得不重新启动整个机器,而不仅仅是 rails 服务器。

于 2013-03-15T13:10:10.663 回答
0

我建议您注释掉国家对象的创建,并首先检查您获得的值是否正确。我使用了您的示例文件并使用与您类似的代码运行它。没有错误。但是由于您以不同的顺序获取值(例如,您可能获取的是名称而不是缩写 - 因此出现错误)。您甚至可以先编写一个简单的 ruby​​ 脚本来读取此文件并打印值。其次,您可以使用csv 模块,它是一个标准的 ruby​​ 模块,用于处理来自 csv 文件的数据。

于 2013-03-16T03:09:04.887 回答