我正在尝试从 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)