2013-01-17 101 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。