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 ...
随机推荐
- C++ 模板详解(一)(转)
C++模板 模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数.返回值取得任意类型. 模板是一种对类型进行参数化的工具: 通常有 ...
- crm使用soap取消用户訪问记录权限
//取消訪问权限 function demo() { //操作记录的id var targetId = "A8A46444-BA10-E411-8A04-00155D002F ...
- 【Excle数据透视表】如何新建数据透视表样式
如果觉得Excle给出的数据透视表样式不符合自己的心意,可以自己定义一个数据透视表样式 步骤1 单击数据透视表区域任意单元格→数据透视表工具→设计→样式组中的下拉按钮,打开数据透视表样式库→新建数据透 ...
- iOS项目开发之仿网易彩票推荐应用
简介 效果展示 思路分析 代码实现 Git地址 一.简介 某些公司有较多的产品时,通常会在一个产品中推广另外的一些产品,我简单的封装了一个UIControllerView,由于不同公司,要求不同.所以 ...
- 多trac的安装和配置
其他相关网页: trac+svn: http://wenku.baidu.com/view/84389a81ec3a87c24028c43f.html apache(GCI):http://hi.ba ...
- 隐藏ion-nav-back-button的文字
<ion-nav-bar class="bar-positive"> <ion-nav-back-button> </ion-nav-back-but ...
- 正则化--Lambda
模型开发者通过以下方式来调整正则化项的整体影响:用正则化项的值乘以名为 lambda(又称为正则化率)的标量.也就是说,模型开发者会执行以下运算: $$\text{minimize(Loss(Data ...
- Guice 学习(七)常量和属性的注入( Constant and Property Inject)
1.常量注入方式 package com.guice.ConstantInjectDemo; import com.google.inject.Binder; import com.google.in ...
- VLOOKUP函数的用法
https://zhidao.baidu.com/question/177265501.html?qbl=relate_question_0&word=%3DVLOOKUP%28B10%2CS ...
- android性能优化学习笔记(加快应用程序启动速度:)
一:安卓中应用程序的启动方式有两种: 冷启动:后台没有该应用进程,系统会重新创建一个进程分配给该应用(所以会先创建和初始化Application类,再创建和初始化MainActivity,包括测量,布 ...