我正在尝试从csv文件中播放一个名为countries的表。其他种子按照我指定的顺序工作,但是这个按字母顺序生成INSERT语句,不能正确映射到csv文件中的字段。表国家/地区具有主键约束但没有序列或默认值。我已经调用了rake db:schema:dump,以防模式出现故障而没有运气。有什么想法吗?
模型
class Country < ActiveRecord::Base
attr_accessible :id, :name, :abbreviation, :area, :population, :internet_users, :last_updated
end
schema.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
seeds.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)
答案 0 :(得分:0)
对我来说,这个问题使我的机器或rails实例处于非常糟糕的状态。我不得不重启整个机器,而不仅仅是rails服务器。
答案 1 :(得分:0)
我建议您注释掉国家/地区对象的创建,并首先检查您获得的值是否正确。我使用了您的示例文件并使用与您类似的代码运行它。没有错误。但是,因为您以不同的顺序获取值(例如,您可能获得名称而不是缩写 - 因此错误)。您甚至可以先编写一个简单的ruby脚本来读取此文件并打印值。 其次,您可以使用csv module这是一个标准的ruby模块来处理来自csv文件的数据。