【问题标题】:Ruby on rails does not create foreign keys on databaseRuby on rails 不会在数据库上创建外键
【发布时间】:2014-11-08 22:21:48
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails model associations


    【解决方案1】:

    没错。 Rails 不会自动添加外键,你必须像你一样在迁移中自己指定它。

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

    您是说即使指定了外键,您也看不到结果?

    【讨论】:

    • 没错,即使采用这种配置,也不会在数据库中创建外键。
    • 您是否还记得将用户分配到城市?也许也可以粘贴您的控制器
    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 2015-05-30
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多