5

我正在使用Rails 4和SQLite。我正在試圖在我的indicators表中添加外鍵。請參閱我下面的代碼導軌中的外鍵4

class Indicator < ActiveRecord::Base 
    belongs_to :objetive 
    belongs_to :responsible, class_name: "Person" 

end 

遷移腳本:

class AddFksToIndicator < ActiveRecord::Migration 
    def change 
     add_reference :indicators, :objective, index: true 
     add_reference :indicators, :responsible, index: true 
    end 
end 

運行遷移一切正常的時候,所以我在控制檯嘗試:

2.0.0p247 :002 > i = Indicator.new 
=> #<Indicator id: nil, name: nil, created_at: nil, updated_at: nil, objective_id: nil, responsible_id: nil> 
2.0.0p247 :002 > i.objective_id = 0 
2.0.0p247 :003 > i.save 

令我驚訝的是,指標已保存,並且沒有obective,id = 0。

最後,我檢查了indicator RS表模式,我也得到:

CREATE TABLE "indicators" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "created_at" datetime, "updated_at" datetime, "objective_id" integer, "responsible_id" integer); 
CREATE INDEX "index_indicators_on_objective_id" ON "indicators" ("objective_id"); 
CREATE INDEX "index_indicators_on_responsible_id" ON "indicators" ("responsible_id"); 

爲什麼沒有對objective_idresponsible_id沒有外鍵約束? 我做錯了什麼?

回答

0

當您使用add_reference時,您需要添加foreign_key: true以獲得該呼叫的外鍵支持。例如:

add_reference :indicators, :objective, index: true, foreign_key: true

默認爲foreign_key: false,如在該文檔here提及。

由於您已經創建了沒有外鍵的遷移,因此您需要創建另一個遷移,並調用add_foreign_key

例如:

def change 
    # add_foreign_key(from_table, to_table) 
    add_foreign_key :indicators, :objectives 
end 

這裏的documentation for add_foreign_key

希望這會有所幫助。