mysql workbench foreign keys_Rails association 中的 foreign keys

问题背景

以 belongs_to association 举例:

在添加 belongs_to 关系的时候,需要在 table 中创建 foreign Keys。 比如下面的例子:

class Order < ActiveRecord::Base

belongs_to :customer

end

建立上面的关系的时候,order table 是如下方式建立的

class CreateOrders < ActiveRecord::Migration

def change

create_table :orders do |t|

t.integer :customer_id

······

end

add_index :orders, :customer_id

end

end

或者是下面的代码

class CreateOrders < ActiveRecord::Migration

def change

create_table :orders do |t|

t.belongs_to :customer, index:true

······

end

end

end

通过观察 rails 中 belongs_to 方法的源码发现,这两个代码是等价的。

通过观察发现,belongs_to 的 association 中在 table 上创建 foreign keys, 也等同于在 table 中建立一个 存放 id 的列,并在该 column 上建立了一个 index。所以这里的 foreign keys 并不是 database 中的 foreign keys。

其他的 association 的 foreign keys 也是同样的建立方法。

问题

理论上来说是否任何一个 integer 的 column 上建立一个 index 都能成为 rails association 中的 foreign keys 呢?

这种 foreign keys 是否在功能上代替了 database 中 foreign keys 的作用了呢? 在我个人看来好像是的,

如果这里 foreign keys 在功能上代替了 database 中的 foreign keys 了话,那么在 database 中去建立 foreign keys 还有什么作用呢?如果无法在功能上代替 foreign keys 的话,那为什么上面的例子中不去在 database 中添加 foreign keys 呢?

功能上替代的意思: 对于 database 中的 foreign key 的作用,(我认为)只是用于 join table。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值