【问题标题】:Why did Rails 5 changed "index" to "foreign key"?为什么 Rails 5 将“索引”更改为“外键”?
【发布时间】:2016-09-29 12:11:24
【问题描述】:

如果你在 Rails 4 中有这个:

t.references :event, index: true

现在您可以在 Rails 5 中使用 foreign_key 而不是 index。我不太明白他们为什么决定这样做,因为功能保持不变,您添加的是索引,而不是该列的外键。

【问题讨论】:

  • 老实说我没看懂你的问题,index选项添加了数据库索引,外键添加了数据库外键。

标签: ruby-on-rails foreign-keys primary-key ruby-on-rails-5


【解决方案1】:

在 Rails 5 中 - 当我们引用模型时,foreign_key 上的索引会自动创建。

Rails 5 中的迁移 API 发生了变化 -

Rails 5 更改了迁移 API,因此即使在运行迁移时 null: false 选项未传递给时间戳,也会自动为时间戳添加 not null。

同样,在几乎所有情况下,我们都希望引用列的索引。所以 Rails 5 不需要引用来拥有index: true。运行迁移时,会自动创建索引。

举个例子——(复制自http://blog.bigbinary.com/2016/03/01/migrations-are-versioned-in-rails-5.html

当你运行rails g model Task user:references

Rails 4 会生成

class CreateTasks < ActiveRecord::Migration
  def change
    create_table :tasks do |t|
      t.references :user, index: true, foreign_key: true
      t.timestamps null: false
    end
  end
end

Rails 5 会生成

class CreateTasks < ActiveRecord::Migration[5.0]
  def change
    create_table :tasks do |t|
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end

【讨论】:

  • 非常详细的答案。但是,如果出于某种原因,我不希望引用被索引怎么办?或者即使我只有 t.references :user, foreign_key: true ,它仍然在 Rails 4 中被隐式索引? --- 现在,我想知道为什么他们甚至没有省略 foreign_key: true
【解决方案2】:

indexforeign_key 是不同的概念,即使在 Rails 5 中也是如此。所以说 Rails 5 将“索引”更改为“外键”是错误的。

Rails 4 到 Rails 5 的变化是index 选项默认为true,所以不需要显式设置。

rails 4.2.5 中的方法 add_reference

:索引

添加适当的索引。默认为 false。


rails 5.2 中的方法 add_reference

:索引

添加适当的索引。默认为真。有关此选项的用法,请参见 add_index。

这就是为什么当您在 rails 5 迁移中生成 references 时,您没有看到 index: true,因为它是默认值。

【讨论】:

    【解决方案3】:

    foreign_keyindex 是完全不同的东西(你可以从他们的名字判断)。

    所以没有任何改变,你仍然可以使用两个。

    您可以查看these docs,了解有关在迁移中建立关联的更多信息。

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      相关资源
      最近更新 更多