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

sec · November 23, 2016 · Last by flemon1986 replied at November 24, 2016 · 1789 hits

最近查看 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 closed this topic. 24 Nov 13:43
sec in 在 rails 中很少注意要建立外键的问题 mention this topic. 17 Mar 03:07
You need to Sign in before reply, if you don't have an account, please Sign up first.