Rails: delete cascade vs dependent destroy

apotry picture apotry · Sep 23, 2012 · Viewed 22k times · Source

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.

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:

Case 1. Using :dependent => :destroy in the user model

Case 2. Defining the table orders in postgres and writing

user_id integer REFERENCES users(id) ON DELETE CASCADE

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?

Answer

Peter Brown picture Peter Brown · Sep 24, 2012

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.

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.