我正在使用 Rails 4 和 SQLite。我正在尝试将外键添加到我的indicators
表中。请在下面查看我的代码
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。
最后,我检查了指标表架构,我得到:
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_id
为什么和上没有外键约束responsible_id
?难道我做错了什么?