如果我定义一个Customer和Order模型,其中Customer"有很多" Orders和Order"属于" Customer,在Rails中我们谈论Order有一个外键到Customer通过customer_id但我们并不是说这是在数据库中强制执行.
由于Rails没有将其定义为数据库级约束,因此存在数据完整性被违反的风险,可能在应用程序之外(或者如果同时收到请求,则在内部?),除非您手动在数据库中强制执行约束.
为什么Rails没有在数据库级别定义外键,或者有没有办法让Rails这样做?
class Customer < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :customer
end
ActiveRecord::Schema.define(:version => 1) do
create_table "customers", :force => true do |t|
t.string "name"
end
create_table "orders", :force => true do |t|
t.string "item_name"
t.integer "customer_id"
end
end
Run Code Online (Sandbox Code Playgroud)