Ruby on rails 建议在我的迁移中使用:foreign_key而不仅仅是添加用户id吗?

Ruby on rails 建议在我的迁移中使用:foreign_key而不仅仅是添加用户id吗?,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我使用的是rails 4.2,我只是想知道如果我在迁移中使用:foreign\u key关键字,而不是仅仅添加用户id列来向我的模型添加关系,是否会有什么不同?是的 关键的区别不在于应用层,而在于数据库层——外键用于使数据库强制执行引用完整性 让我们看一个例子: class User < ActiveRecord::Base has_many :things end class Thing < ActiveRecord::Base belongs_to :user end

我使用的是rails 4.2,我只是想知道如果我在迁移中使用
:foreign\u key
关键字,而不是仅仅添加
用户id
列来向我的模型添加关系,是否会有什么不同?

是的 关键的区别不在于应用层,而在于数据库层——外键用于使数据库强制执行引用完整性

让我们看一个例子:

class User < ActiveRecord::Base
  has_many :things
end

class Thing < ActiveRecord::Base
  belongs_to :user
end
ActiveRecord将允许我们在things表上孤立行:

user = User.create(name: 'Max')
thing = user.things.create
user.destroy
thing.user.name # Boom! - 'undefined method :name for NilClass'
如果我们有外键,数据库将不允许我们销毁
用户
,因为它会留下一个孤立的记录

class CreateThings < ActiveRecord::Migration
  def change
    create_table :things do |t|
      t.belongs_to :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
虽然您可以简单地通过回调来调节这一点,但让DB强制引用完整性通常是一个好主意

# using a callback to remove associated records first
class User < ActiveRecord::Base
  has_many :things, dependent: :destroy
end
#首先使用回调删除相关记录
类用户
是 关键的区别不在于应用层,而在于数据库层——外键用于使数据库强制执行引用完整性

让我们看一个例子:

class User < ActiveRecord::Base
  has_many :things
end

class Thing < ActiveRecord::Base
  belongs_to :user
end
ActiveRecord将允许我们在things表上孤立行:

user = User.create(name: 'Max')
thing = user.things.create
user.destroy
thing.user.name # Boom! - 'undefined method :name for NilClass'
如果我们有外键,数据库将不允许我们销毁
用户
,因为它会留下一个孤立的记录

class CreateThings < ActiveRecord::Migration
  def change
    create_table :things do |t|
      t.belongs_to :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
虽然您可以简单地通过回调来调节这一点,但让DB强制引用完整性通常是一个好主意

# using a callback to remove associated records first
class User < ActiveRecord::Base
  has_many :things, dependent: :destroy
end
#首先使用回调删除相关记录
类用户
probable duplicate of the probable duplicate of of of确保为外键列编制索引——无论如何,您可能会这样做,但如果在数据库中声明了外键,则最好确保这样做。有一种宝石可以帮助你。。。不记得名称…我想您可能正在考虑,但是在以后的迁移中,您不需要使用gem来添加外键或索引-如果您在声明列时使用
own\u to
宏,那么无论如何都可以这样做-请确保为外键列编制索引-您可能无论如何都会这样做,但是,如果在数据库中声明了一个外键,那么最好确保这样做。有一种宝石可以帮助你。。。不记得名称…我想您可能正在考虑,但是在以后的迁移中,您不需要gem来添加外键或索引-如果您在声明列时使用
归属
宏,则无论如何都可以完成此操作