Rails foreign_key 放在哪里?

jiffies · April 21, 2012 · Last by redvoilin replied at April 21, 2012 · 2976 hits

在模型定义关系时,foreign_key 指定一个表的外键,has_many,belongs_to 好像都有这个参数,效果是不是一样的?

首先,数据库里的“外键”abc_id,是放在 belongs_to 所在的模型上的。

比如 a_models has_many b_models,并且 b_models belongs_to a_model,那么, belongs_to 上加 foreign_key,是在找关联对象 a_model 时,select * from a_models where id=b_model_id has_many 上加 foreign_key,是在找关联对象 b_models 时,select * from b_models b_model_id=id

不同位置的 foreign_key,拼出来是不同的 SQL。这样说可以么?

A belongs_to B 在 A 的表中包含 B_id 列。

1 楼的第一种情况不存在吧,既然 a has many b,那么肯定是在 b 中加入 a 的 id 作为外键

You need to Sign in before reply, if you don't have an account, please Sign up first.