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!
foreign key的更多相关文章
- Constraint6:更新外键约束(Foreign Key Constraint)的引用列
在SQL Server中,表之间存在引用关系,引用关系通过创建外键约束(Foreign Key Constraint)实现.如果一个Table中的column被其他Table引用,那么该表是参考表,或 ...
- MySQL主从复制中断,报“Error on master: message (format)='Cannot delete or update a parent row: a foreign key constraint fails' error code=1217” 错误
前几天,发现从库挂了,具体报错信息如下: 分析思路 1. 因为我采用的是选择性复制,只针对以下几个库进行复制: card,upay,deal,monitor,collect.所以,不太可能出现对于sa ...
- SQL Server 2008 R2——TRUNCATE TABLE 无法截断表 该表正由 FOREIGN KEY 约束引用
=================================版权声明================================= 版权声明:原创文章 禁止转载 请通过右侧公告中的“联系邮 ...
- 【MySQL】Create table 以及 foreign key 删表顺序考究。
1.以下是直接从数据库导出的建表语句. 1 -- ---------------------------- 2 -- Table structure for files 3 -- ---------- ...
- MYSQL外键(Foreign Key)的使用
在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束.外键的使用条件:1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说以后的版本有可能支持,但至少目前不支持): ...
- SQL PRIMARY KEY 约束\SQL FOREIGN KEY 约束\SQL CHECK 约束
SQL PRIMARY KEY 约束 PRIMARY KEY 约束唯一标识数据库表中的每条记录. 主键必须包含唯一的值. 主键列不能包含 NULL 值. 每个表都应该有一个主键,并且每个表只能有一个主 ...
- 无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用。
在删除northwindcs表时,发生报错,消息 3726,级别 16,状态 1,第 2 行,无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用.此时判断是因为有其他表的外键 ...
- 解决Cannot delete or update a parent row: a foreign key constraint fails (`current_source_products`.`product_storage`, CONSTRAINT `product_storage_ibfk_3` FOREIGN KEY (`InOperatorID`)
出现这个异常的原因是因为设置了外键,造成无法更新或删除数据. 1.通过设置FOREIGN_KEY_CHECKS变量来避免这种情况 删除前设置 SET FOREIGN_KEY_CHECKS=0; 删除完 ...
- Hibernate -- A unidirectional one-to-one association on a foreign key
at sometime we usually need to create two tables that one table relate another.Such as a husband onl ...
- 使用ABP时报错“UPDATE 语句与 FOREIGN KEY SAME TABLE 约束"FK_dbo.AbpUsers_dbo.AbpUsers_LastModifierUserId"冲突”的解决办法
ABP理论学习总目录 一步一步使用ABP框架搭建正式项目系列教程 ABP之Module-Zero学习目录 本篇目录 问题 原因 解决办法 问题 问题的是在下面这种情况下出现的: 我在使用CodeFir ...
随机推荐
- Velocity.js动画库使用
1.简介 Velocity 是一个简单易用.高性能.功能丰富的轻量级JS动画库.它能和 jQuery 完美协作,并和$.animate()有相同的 API, 但它不依赖 jQuery,可单独使用. 2 ...
- Odoo many2many command
CREATE = lambda values: (0, False, values) // (0,False, Values) //创建 UPDATE = lambda id, values: (1, ...
- apue学习笔记(第一章UNIX基础知识)
总所周知,UNIX环境高级编程是一本很经典的书,之前我粗略的看了一遍,感觉理解得不够深入. 听说写博客可以提高自己的水平,因此趁着这个机会我想把它重新看一遍,并把每一章的笔记写在博客里面. 我学习的时 ...
- JavaSE入门学习21:Java面向对象之接口(interface)(二)
一接口实现的多态 在上一篇博文:JavaSE入门学习20:Java面向对象之接口(interface)(一)中提到了接口的实现存在多态性,那么 这一篇主要就要分析接口实现的多态. 实例一 Test.j ...
- Fiddler 默认不能抓取页面信息的问题
先如下配置
- spring的xml配置文件出现故障
今天在断网的情况下,spring的applicationContext.xml文件开头部分出现红叉 <span style="font-size:18px;">< ...
- TransactionScope的用法
using (TransactionScope ts = new TransactionScope()) { Model.user_login_log model = new Model.user_l ...
- JavaScript_DOM编程艺术第二版[阅]
前两年迫于项目的需要,只是拿来JQuery用到项目中,并没有实质上理解javascript(貌似其他人也是这么干的)~ 随着最近几年,得益于Nodejs, React, Vue等,javascript ...
- left join,right join用法简介
方法一(推荐): select a.man_id,man_name,d.sex_name,zw_name,c.money from man as a left join zw as b on a.zw ...
- web 开发之js---js 实现自动添加input text 编辑框
<html><head><script type="text/javascript">function addNewLine(){var for ...