Rails 4中的外键

6

我正在使用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

令我惊讶的是,指标被保存了,并且没有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_idresponsible_id上没有外键约束? 我做错了什么吗?

SQLite 确实支持外键,因此,有志于使用SQLite的人可以改进适配器以支持外键。但是,只需在开发中切换到使用Postgres就容易得多了。这将为您带来许多其他好处,因此这真的是一个不需要思考的选择。SQLite对于它所构建的用途来说非常棒,但是Rails开发并不是它的理想用例。运行Postgres并不难,而且在开发中使用与生产中相同的数据库是有意义的。 - iconoclast
2个回答

9

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

这里是add_foreign_key的文档

希望能对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接