外键在轨道4 [英] Foreign key in rails 4

查看:157
本文介绍了外键在轨道4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails 4和SQLite。我试图添加外键到我的指标表。请参阅下面的代码

  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
我做错了什么?

解决方案根据 Ruby on Rails 4.2发行说明,只有mysql,mysql2和postgresql适配器支持外键。



不幸的是,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆