我有一系列sql语句,我正在读到我的数据库 - 特别是,我正在播种一个带有城市和坐标的表,但是有点困惑,因为如何处理sql转储中缺少的ID列。
我要创建表格的迁移:
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
运行迁移后:
sqlite> PRAGMA table_info(cities_extended)
0|id|INTEGER|1||1
1|city|varchar(255)|0||0
2|state_code|varchar(255)|0||0
3|zip|integer|0||0
4|latitude|float|0||0
5|longitude|float|0||0
6|county|varchar(255)|0||0
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的额外列。这可以防止表格被播种。满足色谱柱要求的最佳方法是什么?
答案 0 :(得分:1)
如果确实需要默认id列,则可以修改INSERT sql以指定使用的列:
INSERT INTO `cities_extended` (city, state_code, zip, latitude, longtitude, county) VALUES ('Holtsville', 'NY', '00501', '40.8152', '-73.0455', 'Suffolk');
这应该为您提供由表生成的正常自动递增的id列。
答案 1 :(得分:0)
所以我找到了一个解决方法,但我不相信它是最好的方法:
class CreateCitiesExtended < ActiveRecord::Migration
def change
create_table :cities_extended, :id => false do |t|
设置:id =&gt; false允许我绕过要求。
它适用于我的事业,但我不确定它是最好的方法,因为任何记录都不会有任何唯一的ID。如果有人知道更好的方法,我会留下问题吗?
来源:Create an ActiveRecord database table with no :id column?
答案 2 :(得分:0)
添加迁移以填充数据。在该迁移中,创建您的记录。
class MigrateCities < ActiveRecord::Migration
def change
CitiesExtended.create(:city => "Holtsville", :state_code => "NY", :zip => "00501", rest of fields)
rinse, repeat
end
end
您需要确定Zip是否真的是整数。 Zip + 4表示您应该使用字符串,而不是整数。