最近查看 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
===============