2013-01-17 102 views
0

我在鐵軌一個非常簡單的遷移腳本,Rails的遷移創建表

class CreateGeocode < ActiveRecord::Migration 
def up 
    create_table :geocodes do |t|  
    t.string :zip_code, :null => false 
    t.float :latitude 
    t.float :longitude 
    t.string :country_code 
    t.timestamps  
    end 
end 

def down 
    drop_table :geocodes 
end 
end 

當我遷移到這個數據庫。它創建一個名稱爲地理編碼的表格。現在,當我嘗試它像插入一條記錄,

g = Geocode.new(:zip_code => '27606') 
g.save 

通過軌道控制檯,這是結果,我得到的,

mysql> select * from geocodes; 

+-------+----------+----------+-----------+--------------+---------------------+---------------------+ 
| id | zip_code | latitude | longitude | country_code | created_at   | updated_at   | 
+-------+----------+----------+-----------+--------------+---------------------+---------------------+ 
| 27606 | 27606 |  NULL |  NULL | NULL   | 2013-01-17 08:10:34 | 2013-01-17 08:10:34 | 
+-------+----------+----------+-----------+--------------+---------------------+---------------------+ 
1 row in set (0.00 sec) 

爲什麼ID走的是相同的值郵政編碼的?

任何猜測?

回答

0

我想自己回答,因爲我在代碼中發現了我的錯誤。

我偶然將zip_code設置爲模型中的主鍵。 這就是場景發生的原因。

這是我的錯誤。 Rails將zip_code + id作爲主鍵並將相同的值設置爲id和zip_code。