外键在轨道4 [英] Foreign key in rails 4
问题描述
指标
表。请参阅下面的代码 class指标< 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
=> #<指标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 TABLEindicators(idINTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,namevarchar(255),created_atdatetime,updated_atdatetime,objective_id integer,responsible_idinteger);
CREATE INDEXindex_indicators_on_objective_idON指标(objective_id);
CREATE INDEXindex_indicators_on_responsible_idON指标(responsible_id);
为什么在 objective_id
和 responsible_id
?
我做错了什么?
不幸的是,sqlite3适配器没有。
I'm using Rails 4 and SQLite. I'm trying to add foreing keys to my indicators
table. Please see my code below
class Indicator < ActiveRecord::Base
belongs_to :objetive
belongs_to :responsible, class_name: "Person"
end
The migration script:
class AddFksToIndicator < ActiveRecord::Migration
def change
add_reference :indicators, :objective, index: true
add_reference :indicators, :responsible, index: true
end
end
when run the migration all is ok, so I tried in console:
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
To my surprise, the indicator was saved and there is no obective
with id = 0.
Finally, I checked the indicators table schema and I get:
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");
Why there is no foreign key constraint on objective_id
and responsible_id
?
Am I doing something wrong?
According to Ruby on Rails 4.2 Release notes, only the mysql, mysql2 and postgresql adapters support foreign keys.
Unfortunately, the sqlite3 adapter does not.
这篇关于外键在轨道4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!