新手问题 在 Model 中声明关系后,是否有必要数据表中创建将该字段设置为外键?

sec · 2016年11月23日 · 最后由 flemon1986 回复于 2016年11月24日 · 1789 次阅读

最近查看 RubyGuides 发现疑问,在模型中声明关系后,是否有必要数据表中创建将该字段设置为外键?看起来功能相同.

#创建外键   
 def change
    create_table :client do |t|
      t.string :name
      t.references :address, index: true, foreign_key: true
    end
 end

#个人感觉这样更合理,没有创建外键   
 def change
    create_table :client do |t|
      t.string :name
      t.integer :address_id
    end
 end
 ==============   
class Client < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
  belongs_to :client
end
===============

可以不用的

#1 楼 @huacnlee 谢谢,我以后尽量用模型层的关联方法,数据库层关联有点复杂。

外键这种东西只在教科书上学学就可以了,跟着老师做个选课系统什么的。 真正开发并不太多场景用到。

数据表设置外键有个保护作用,其实挺有用的,可以防止删除被关联的数据而导致其他数据错误读取的情况

sec 关闭了讨论。 11月24日 13:43
sec 在 rails 中很少注意要建立外键的问题 提及了此话题。 03月17日 03:07
需要 登录 后方可回复, 如果你还没有账号请 注册新账号