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的更多相关文章

  1. Constraint6:更新外键约束(Foreign Key Constraint)的引用列

    在SQL Server中,表之间存在引用关系,引用关系通过创建外键约束(Foreign Key Constraint)实现.如果一个Table中的column被其他Table引用,那么该表是参考表,或 ...

  2. 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 ...

  3. SQL Server 2008 R2——TRUNCATE TABLE 无法截断表 该表正由 FOREIGN KEY 约束引用

    =================================版权声明================================= 版权声明:原创文章 禁止转载  请通过右侧公告中的“联系邮 ...

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

    1.以下是直接从数据库导出的建表语句. 1 -- ---------------------------- 2 -- Table structure for files 3 -- ---------- ...

  5. MYSQL外键(Foreign Key)的使用

    在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束.外键的使用条件:1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说以后的版本有可能支持,但至少目前不支持): ...

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

    SQL PRIMARY KEY 约束 PRIMARY KEY 约束唯一标识数据库表中的每条记录. 主键必须包含唯一的值. 主键列不能包含 NULL 值. 每个表都应该有一个主键,并且每个表只能有一个主 ...

  7. 无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用。

    在删除northwindcs表时,发生报错,消息 3726,级别 16,状态 1,第 2 行,无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用.此时判断是因为有其他表的外键 ...

  8. 解决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; 删除完 ...

  9. 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 ...

  10. 使用ABP时报错“UPDATE 语句与 FOREIGN KEY SAME TABLE 约束"FK_dbo.AbpUsers_dbo.AbpUsers_LastModifierUserId"冲突”的解决办法

    ABP理论学习总目录 一步一步使用ABP框架搭建正式项目系列教程 ABP之Module-Zero学习目录 本篇目录 问题 原因 解决办法 问题 问题的是在下面这种情况下出现的: 我在使用CodeFir ...

随机推荐

  1. DNS检测

    dig @58.241.41.152 6900255264940.barcode.cniotroot.cn naptr 没有naptr 好像有点异常 select count(*) as total ...

  2. Nginx:subrequest的使用方式

    参考资料<深入理解Nginx> subrequest是由HTTP框架提供的一种分解复杂请求的设计模式. 它可以把原始请求分解为许多子请求,使得诸多请求协同完成一个用户请求,并且每个请求只关 ...

  3. swift 可变參数

    func sumof(numbers:Int...)->Int{  var sum = 0;  for number in numbers{   sum+=number;  }  return ...

  4. APP开发关于缓存

    1 http://www.cnblogs.com/qianxudetianxia/archive/2012/02/20/2112128.html 1.1 http://blog.csdn.net/ln ...

  5. GridControl 二次封装,自定义颜色样式风格

    1.自定义颜色格式,分组,筛选 1.封装类 必须引用类库 using System; using System.Collections.Generic; using System.Linq; usin ...

  6. MySQL5.5中文支持

    1. /etc/my.cnf.d/client.cnf [client] #password = [your_password] port = 3306 socket = /tmp/mysql.soc ...

  7. 读书报告之《改动代码的艺术》 (I)

    <改动代码的艺术>,英文名<Working Effectively with Legacy Code>,中文翻译的文笔上绝对谈不上"艺术"二字.愧对艺术二字 ...

  8. [转] java代码块 介绍

    //执行顺序:(优先级从高到低.)静态代码块>mian方法>构造代码块>构造方法. 其中静态代码块只执行一次.构造代码块在每次创建对象是都会执行. 1 普通代码块 1 //普通代码块 ...

  9. SVN 创建仓库操作

    服务端安装完成后 1.创建一个存放仓库的文件夹(这里在home目录创建) #mkdir svnRepo #cd svnRepo/ 创建一个仓库 (写全路径) # svnadmin create /ro ...

  10. pycharm的安装和破解

    前提: 为了学习爬虫,单独下载了一个pycharm编辑器,所以就有了这篇文章,和PHPstorm的安装和破解及其类似, 如有想了解PHPstorm的安装破解可参考我的另一篇博文:http://www. ...