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?
Therefore, other similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks. :destroy causes all the associated objects to also be destroyed. :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.
ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly you want to delete this order, which consists of a header and some lines.
Because ON DELETE CASCADE is specified for the dependent table, when a row of the all_candy table is deleted, the corresponding rows of the hard_candy table are also deleted.
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.
has_many :orders, dependent: :destroy
add_foreign_key :orders, :users, on_delete: :cascade
(in database migration)
has_many :orders, dependent: :delete_all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With