2014-11-08 98 views
0

Rails不会在数据库上创建外键是正常吗?或者我做错了什么?Ruby on Rails不会在数据库上创建外键

我有这些模型:

class City < ActiveRecord::Base 
    has_many :users 
end 

class User < ActiveRecord::Base 
    belongs_to :city 
end 

及其各自的迁移:

class CreateCities < ActiveRecord::Migration 
    def change 
    create_table :cities do |t| 
     t.string :name 
     t.timestamps 
    end 
    end 
end 

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :name 
     t.references :city, index: true 
     t.timestamps 
    end 
    end 
end 

回答

0

这是正确的。 Rails不会自动添加外键,你必须像你一样在迁移中自己指定它。

t.references :city实际上与t.integer :city_id相同。

你是说即使指定了一个外键,你没有看到结果?

+0

即使使用此配置,也不会在数据库中创建外键。 – arielmcm 2014-11-08 23:18:20

+0

您是否尝试过使用t.integer:city_id? – doz87 2014-11-08 23:20:00

+0

你是否还记得将用户分配到城市?也许粘贴你的控制器 – doz87 2014-11-08 23:21:43