foreign key

http://sevenseacat.net/2015/02/24/add_foreign_key_gotchas.html

https://robots.thoughtbot.com/referential-integrity-with-foreign-keys

保证数据库级别参照完整性

`add_foreign_key` gotchas in Rails 4.2
Feb 24, 2015 | Programming, Rails
Rails 4.2 finally added native support for database-level foreign keys, which is great. You can write the following code in a migration (assuming the presence of a users table):
def change
  create_table :posts do |t|
    t.references :user, index: true
  end
  add_foreign_key :posts, :users
end
And Rails will apply its conventions and infer what you expect:
Column   |  Type   |                     Modifiers
---------+---------+----------------------------------------------------
 id      | integer | not null default nextval(‘posts_id_seq‘::regclass)
 user_id | integer |
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)
    "index_posts_on_user_id" btree (user_id)
Foreign-key constraints:
    "fk_rails_cbe63c1bd4" FOREIGN KEY (user_id) REFERENCES users(id)
We have a database-level foreign key pointing from the user_id column of the posts table, to the id column of the posts table. You can specify all of the expected options for the foreign key - on_delete, on_cascade, etc. This will work just fine in both PostgreSQL and MySQL - it’s a no-op in every other ActiveRecord adapter (including SQLite!)
The problem is when you want to name your associations and columns more semantically - a post doesn’t have a user, it has an author. So you generate your model nicely on the command line:
$ bin/rails g model Post author:references
Which generates a migration that includes:
def change
  create_table :posts do |t|
    t.references :author, index: true
  end
  add_foreign_key :posts, :authors
end
This will error out when you try to run the migration:
== [timestamp] CreatePosts: migrating =====================================
-- create_table(:posts)
   -> 0.0382s
-- add_foreign_key(:posts, :authors)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedTable: ERROR:  relation "authors" does not exist
: ALTER TABLE "posts" ADD CONSTRAINT "fk_rails_2cb0a9abaa"
FOREIGN KEY ("author_id")
  REFERENCES "authors" ("id")
...
Rails’ automatic inference has failed - it doesn’t know that our author association is actually to the users table.
To fix this, you can modify the migration before running it, and configure which column the foreign key should use, and which table the key should point to:
add_foreign_key :posts, :users, column: :author_id
And then the foreign key is created as you would expect:
  Column     |  Type   |                      Modifiers
-----------+---------+-----------------------------------------------------
 id        | integer | not null default nextval(‘posts_id_seq‘::regclass)
 author_id | integer |
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)
    "index_posts_on_author_id" btree (author_id)
Foreign-key constraints:
    "fk_rails_5492f4e861" FOREIGN KEY (author_id) REFERENCES users(id)
Success! Rails can do some amazing things when it comes to following its conventions, but sometimes it requires a little help to take full advantage of the functionality it provides. I hope this helps someone!
时间: 2024-11-05 19:03:05

foreign key的相关文章

SQL FOREIGN KEY 约束

SQL FOREIGN KEY 约束 一个表中的 FOREIGN KEY 指向另一个表中的 PRIMARY KEY. 让我们通过一个例子来解释外键.请看下面两个表: "Persons" 表: Id_P LastName FirstName Address City 1 Adams John Oxford Street London 2 Bush George Fifth Avenue New York 3 Carter Thomas Changan Street Beijing &qu

mysql中的外键foreign key

一.如果一张表中有一个非主键的字段指向了别一张表中的主键,就将该字段叫做外键. 一张表中可以有多个外键. 外键的默认作用有两点: 1.对子表(外键所在的表)的作用:子表在进行写操作的时候,如果外键字段在父表中找不到对应的匹配,操作就会失败. 2.对父表的作用:对父表的主键字段进行删和改时,如果对应的主键在子表中被引用,操作就会失败. 外键的定制作用----三种约束模式: district:严格模式(默认), 父表不能删除或更新一个被子表引用的记录. cascade:级联模式, 父表操作后,子表关

MySQL Foreign Key

ntroduction to MySQL foreign key A foreign key is a field in a table that matches another field of another table. A foreign key places constraints on data in the related tables, which enables MySQL to maintain referential integrity. Let’s take a look

SQL PRIMARY KEY 约束\SQL FOREIGN KEY 约束\SQL CHECK 约束

SQL PRIMARY KEY 约束 PRIMARY KEY 约束唯一标识数据库表中的每条记录. 主键必须包含唯一的值. 主键列不能包含 NULL 值. 每个表都应该有一个主键,并且每个表只能有一个主键. SQL PRIMARY KEY Constraint on CREATE TABLE 下面的 SQL 在 "Persons" 表创建时在 "Id_P" 列创建 PRIMARY KEY 约束: MySQL: CREATE TABLE Persons ( Id_P i

SQLServer FOREIGN KEY ON DELETE CASCADE 限制条件

在需要实现级联删除的情况下,使用 FOREIGN KEY的ON DELETE CASCADE选项非常方便,但在同一张表中,如果有两个外键引用外表数据,那么最多只能将一个外键设为 ON DELETE CASCADE,其他的引用约束需要使用触发器实现级联删除. 1 --建立单词表 2 IF EXISTS (SELECT * FROM sysobjects WHERE name='Word') 3 DROP TABLE Word 4 CREATE TABLE Word 5 ( 6 wordID int

Oracle之外键(Foreign Key)用法详解(二)- 级联删除(DELETE CASCADE)

Oracle外键(Foreign Key)之级联删除(DELETE CASCADE) 目标 示例讲解如何在Oracle外键中使用级联删除 什么是级联删除(DELETE CASCADE)? 级联删除是指当主表(parent table)中的一条记录被删除,子表中关联的记录也相应的自动删除. 外键的级联删除可以在创建表时定义,也可以使用ALTER TABLE语法定义. 创建表时定义级联删除 语法: CREATE TABLE table_name ( column1 datatype null/not

【MySQL】Create table 以及 foreign key 删表顺序考究。

1.以下是直接从数据库导出的建表语句. 1 -- ---------------------------- 2 -- Table structure for files 3 -- ---------------------------- 4 DROP TABLE IF EXISTS `files`; 5 CREATE TABLE `files` ( 6 `id` int(11) NOT NULL, 7 `fileName` varchar(50) DEFAULT NULL, 8 `filePat

oracle约束总结(not null/unique/primary key/foreign key/check)

约束(constraint):对创建的表的列属性.字段进行的限制.诸如:not null/unique/primary key/foreign key/check 作用范围: ①列级约束只能作用在一个列上 ②表级约束可以作用在多个列上(当然表级约束也可以作用在一个列上) 定义方式:列约束必须跟在列的定义后面,表约束不与列一起,而是单独定义. - -NOT NULL:不为空约束,只能定义在列级 CREATE TABLE employees( employee_id NUMBER(6), --<sp

更改具有Foreign key约束的表

1.Foreign key 说明: foreign key(外键) 建立起了表与表之间的约束关系,让表与表之间的数据更具有完整性和关联性.设想,有两张表A.B,A表中保存了许多电脑制造商的信息,比如联想.戴尔.惠普和华硕,B表中保存了许多多型号的电脑,比如lenovo1,lenovo2,hp1,hp2,hp3,dell1,dell2,asus1,现在如何将两张具有从属关系(每个电脑品牌下都有很多型号的电脑)的表关联起来呢? 我们可以在B表中设置外键.首先我们给这个外键关联关系起个名字xx,外键作

Mysql create constraint foreign key faild.trouble shooting method share

mysql> create table tb_test (id int(10) not null auto_increment primary key,action_id int(10) not null,error_code int(10) not null default 0,desc_key varchar(64) not null default 'audit.log.default',INDEX(action_id),constraint `FK_ACTIONID` foreign k