Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

postgresql - Rails: delete cascade vs dependent destroy

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...