2013-10-13 49 views
0

我有一系列的sql語句,我正在讀入我的數據庫 - 特別是,我播種了一個城市和座標表,但有點困惑,因爲如何處理丟失的ID列在sql轉儲。rails導入sql,列id不匹配

我的遷移創建表:

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文件看起來是這樣的:

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 

運行遷移後

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 

正如您從遷移表中看到的,額外的一個名爲id的列是由rails創建的。這可以防止表格被播種。滿足色譜柱要求的最佳方法是什麼?

回答

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列如表中生成的那樣。

+0

給了這個鏡頭,它工作得很漂亮!謝謝 – lfender6445

0

所以,我發現周圍的工作,但我不相信它的最好辦法:

class CreateCitiesExtended < ActiveRecord::Migration 
    def change 
     create_table :cities_extended, :id => false do |t| 

設置:ID =>假,讓我繞過的要求。

它適用於我的原因,但我不確定它的最佳方式,因爲任何記錄上都不會有任何唯一的ID。如果有人知道更好的方法,我會讓問題保持開放。

來源:Create an ActiveRecord database table with no :id column?

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將表示您應該使用字符串,而不是整數。