rails导入sql,id上的列不匹配
我有一系列的sql语句,我正在读取到我的db中——具体地说,我正在播种一个包含城市和坐标的表,但是对于如何处理sql转储中缺少的ID列有点困惑 我的迁移以创建表:rails导入sql,id上的列不匹配,sql,ruby-on-rails,sqlite,Sql,Ruby On Rails,Sqlite,我有一系列的sql语句,我正在读取到我的db中——具体地说,我正在播种一个包含城市和坐标的表,但是对于如何处理sql转储中缺少的ID列有点困惑 我的迁移以创建表: class CreateCitiesExtended < ActiveRecord::Migration def change create_table :cities_extended do |t| t.string :city t.string :state_code t.in
class CreateCitiesExtended < ActiveRecord::Migration
def change
create_table :cities_extended do |t|
t.string :city
t.string :state_code
t.integer :zip
t.float :latitude
t.float :longitude
t.string :county
end
end
def down
drop_table :cities_extended
end
end
sql文件如下所示:
INSERT INTO `cities_extended` VALUES ('Holtsville', 'NY', '00501', '40.8152', '-73.0455', 'Suffolk');
INSERT INTO `cities_extended` VALUES ('Holtsville', 'NY', '00544', '40.8152', '-73.0455', 'Suffolk');
INSERT INTO `cities_extended` VALUES ('Adjuntas', 'PR', '00601', '18.1788', '-66.7516', 'Adjuntas');
但是,当我尝试将.sql文件读入sqlite表时,会出现列不匹配错误:
rails db
sqlite> .read ./db/data/cities_extended.sql
Error: near line 41780: table cities_extended has 7 columns but 6 values were supplied
Error: near line 41781: table cities_extended has 7 columns but 6 values were supplied
从迁移的表中可以看到,rails创建了一个名为id的额外列。这将防止表格被播种。满足立柱要求的最佳方式是什么 所以我找到了一个解决办法,但我不认为这是最好的办法:
class CreateCitiesExtended < ActiveRecord::Migration
def change
create_table :cities_extended, :id => false do |t|
class CreateCitiesExtendedfalse do | t|
设置:id=>false允许我绕过需求
它对我的事业有效,但我不确定这是最好的方式,因为任何记录上都不会有任何唯一的ID。如果有人知道更好的方法,我会把这个问题留着讨论
来源:如果确实需要默认id列,可以修改INSERT sql以指定使用的列:
INSERT INTO `cities_extended` (city, state_code, zip, latitude, longtitude, county) VALUES ('Holtsville', 'NY', '00501', '40.8152', '-73.0455', 'Suffolk');
这将为您提供由表生成的正常自动递增id列。添加迁移以填充数据。在该迁移中,创建记录
class MigrateCities < ActiveRecord::Migration
def change
CitiesExtended.create(:city => "Holtsville", :state_code => "NY", :zip => "00501", rest of fields)
rinse, repeat
end
end
class MigrateCities“Holtsville”,:state\u code=>“NY”,:zip=>“00501”,其余字段)
冲洗,重复
结束
结束
您需要确定您的Zip是否真的是一个整数。Zip+4表示应该使用字符串,而不是整数
class MigrateCities < ActiveRecord::Migration
def change
CitiesExtended.create(:city => "Holtsville", :state_code => "NY", :zip => "00501", rest of fields)
rinse, repeat
end
end