5

私はRails 4とSQLiteを使用しています。 indicatorsテーブルにforeingキーを追加しようとしています。インジケータ、驚いたことにレール内の外部キー4

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 

:移行を実行すると

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

すべてがOKですので、私はコンソールで試行:

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

end 

移行スクリプト以下の私のコードを参照してください。が保存され、id = 0であるobectiveがありません。

最後に、 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には外部キー制約が存在しないのはなぜ? 何か間違っていますか?

答えて

8

Ruby on Rails 4.2 Release notesによると、mysql、mysql2、およびpostgresqlアダプタのみが外部キーをサポートしています。

残念ながら、sqlite3アダプタはありません。

0

add_referenceを使用している場合は、foreign_key: trueを追加してその呼び出しで外部キーをサポートする必要があります。例:ドキュメントhereで述べたように

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

デフォルトでは、foreign_key: falseです。

すでに外部キーなしで移行を作成しているので、add_foreign_keyを呼び出して別の移行を作成する必要があります。例えば

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

ここdocumentation for add_foreign_keyです。

これが役に立ちます。