7

继指导,我跑以下命令:指数:真正VS foreign_key:真(Rails)的

rails g migration CreateSnippetsUsers snippet:belongs_to user:belongs_to 

这创造了以下迁移:

class CreateSnippetsUsers < ActiveRecord::Migration[5.0] 
    def change 
    create_table :snippets_users do |t| 
     t.belongs_to :snippet, foreign_key: true 
     t.belongs_to :user, foreign_key: true 
    end 
    end 
end 

在过去,我已经看到了同样的事情,但用index: true而不是foreign_key: true。两者有什么区别?

+0

http://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4可能这将有助于 – Bijendra

回答

0

为了获得良好性能,您可以添加index: trueforeign_key: true,但这不是必需的。

索引为数据库中的搜索提供了更好的选择,因此速度更快。

外键强制执行参照完整性。您可以阅读关于外键的更多信息here

+0

这是危险的信息。索引提供更好的读取效率。权衡是WRITES比较慢 – TheRealMrCrowley

7

索引可提高数据库表上数据检索操作的速度。当我们将index: true写入任何列时,它会向此列添加数据库索引。比如我创建一个表:

create_table :appointments do |t| 
     t.references :student, index: true 
    end 

它将appointments表中创建student_id列。

一个外键有不同的用例,它是表之间的关系。它允许我们在一个表中声明一个与另一个表中的索引相关的索引,并且还放置了一些约束。数据库强制执行这种关系的规则以保持参照完整性。例如,我们有两个表profileseducations,一个配置文件可能有许多教育。

create_table :educations do |t| 
    t.belongs_to :profile, index: true, foreign_key: true 
end 

现在,我们在educations表是profiles表的外键profile_id列。它阻止将记录输入到educations表中,除非其中包含profiles表中存在的profile_id值。因此参考性将保持不变。

+0

没有't.references:学生'在'约会'表中创建'student_id'列?如果是这样,那么'index:true'是做什么的? – Mirror318

+0

index:true在这里编制索引。 –