Rails:删除级联与依赖破坏 [英] Rails: delete cascade vs dependent destroy
问题描述
假设我有两个表: users
和 orders
。一个用户有很多订单,因此我的订单表中自然会有一个外键user_id。
Assuming I have two tables: users
and orders
. A user has many orders, so naturally there is a foreign key user_id in my orders table.
在rails上的最佳做法是什么(在速度,样式和引用方面)完整性)以确保如果删除用户,所有相关订单也被删除?我正在考虑以下选项:
What is the best practice in rails (in terms of speed, style and referential integrity) to ensure that if a user is deleted, all dependent orders are also deleted? I am considering the following options:
情况1.使用:dependent => :用户模型中的:destroy
案例2。在postgres中定义表顺序并编写
Case 2. Defining the table orders in postgres and writing
user_id integer REFERENCES users(id) ON DELETE CASCADE
我应该使用案例1吗?似乎案例2正在做我想做的所有事情?在执行速度方面有区别吗?
Is there any reason why I should use Case 1? It seems that Case 2 is doing all I want it to do? Is there are difference in terms of execution speed?
推荐答案
这实际上取决于您想要的行为。在情况1中,将在每个关联的订单上调用destroy,因此, ActiveRecord回调。在情况2中,不会触发这些回调,但是会更快,并且可以确保引用完整性。
It really depends on the behavior you want. In case 1, destroy will be called on each associated order, and therefor so will the ActiveRecord callbacks. In case 2, these callbacks are not triggered, but it will be way faster and guarantees referential integrity.
在应用程序初期,我建议使用:dependent => :destroy
因为它使您可以以独立于数据库的方式进行开发。一旦开始扩展,出于性能/完整性的原因,应该开始在数据库中进行扩展。
In an application's infancy, I'd recommend going with :dependent => :destroy
because it lets you develop in a way that is independent of the database. Once you start to scale, you should start doing it in the database for performance/integrity reasons.
这篇关于Rails:删除级联与依赖破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!