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在這裏編制索引。 –