为什么Rails 5更改了“索引"?到“外键"? [英] Why did Rails 5 changed "index" to "foreign key"?
问题描述
如果您在Rails 4中有此功能:
If you had this in Rails 4:
t.references :event, index: true
现在您可以在Rails 5中使用foreign_key
代替index
.我不太明白为什么他们决定这样做,因为功能保持不变,您要添加的是INDEX,而不是该列的外键.
Now you could use foreign_key
instead of index
in Rails 5. I don't quite understand WHY they decided to do this, since the functionality remains the same, what you're adding is an INDEX, not a FOREIGN KEY to that column.
推荐答案
在Rails 5中-当我们引用模型时,会自动创建foreign_key
上的索引.
In Rails 5 - when we reference a model, index on the foreign_key
is automatically created.
迁移API在Rails 5中已更改-
Migration API has changed in Rails 5 -
Rails 5更改了迁移API,因此,即使在运行迁移时未将null: false
选项传递给时间戳,也不会为时间戳自动添加非null.
Rails 5 has changed migration API because of which even though null: false
options is not passed to timestamps when migrations are run then not null is automatically added for timestamps.
类似地,几乎在所有情况下,我们都希望为被引用的列创建索引.因此,Rails 5不需要引用即可具有index: true
.运行迁移后,会自动创建索引.
Similarly, we want indexes for referenced columns in almost all cases. So Rails 5 does not need references to have index: true
. When migrations are run then index is automatically created.
例如-(从 http://blog.bigbinary.com/2016/03/01/migrations-are-versioned-in-rails-5.html )
当您运行rails g model Task user:references
路轨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会生成
And rails 5 would generate
class CreateTasks < ActiveRecord::Migration[5.0]
def change
create_table :tasks do |t|
t.references :user, foreign_key: true
t.timestamps
end
end
end
这篇关于为什么Rails 5更改了“索引"?到“外键"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!