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. 【Datastage】Datastage在win10上安装报错:This Application requires one of the following versions of the .NET Framework:v1.1.4322 Do you want to install this .NET Framework version now?

    Datastage在win10上安装报错如下: 这个错误的意思是:.netFramWork的版本不符合要求,于是,我在网上下载了一个版本一致的 下载地址为:http://pan.baidu.com/s ...

  2. Android 冷兵器 之 tools

    代码地址如下:http://www.demodashi.com/demo/12612.html 前言 Android开发在所难免的就是UI的预览和调整,一般情况下都是直接run看效果,或者是使用AS的 ...

  3. int a[3];中a+1与&a+1差别 -- C

    int a[3]; a 和 &a 的地址一样的. a+1 == a + 1*sizeof(int);跳跃是一个数组元素大小 &a+1 == a + 3*sizeof(int);跳跃是整 ...

  4. nightwatchjs --Expect element to not include text

    to have NightWatch to find text in a div. browser.assert.containsText('#output', 'find me') But how ...

  5. java 中的 i++ 和 ++i

    熟悉c/c++中的i++和++i,那么你知道下面的java代码效果是什么吗? 一 . 代码示例 /** * * @author elelule * */ public class TestPlusPl ...

  6. leetCode 15. 3Sum (3数之和) 解题思路和方法

    3Sum  Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find ...

  7. Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: DexPathList[[zip file "/data/app/*** *** ***-2/base.apk"],nativeLibraryDirectories

    Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: Dex ...

  8. Spring Cloud Zuul 网关的分布式系统中整合Swagger(转)和 zuul跨域访问问题

    首先恭喜自己终于找对了努力的方向,很荣幸能在公司接触到微服务架构,也很高兴公司一个大佬哥们愿意带我,他技术确实很牛逼,我也很佩服他,前后端通吃,干了六年能有这样的水平.最近跟着在搞微服务架构,给我分配 ...

  9. jar包解压与打包

    首先感谢大神的指导:https://blog.csdn.net/mr_pang/article/details/47028921 1.首先准备一个能运行的jar文件,我们使用第三方解压工具进行解压wi ...

  10. 实现Nullable 可空类型

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace demo ...