NoteIf you want to use foreign key constraints instead for referential integrity, enable foreign key constraint support in your database settings page. If you are unsure if you should use them, the foreign key constraints documentation covers some of the advantages and disadvantages.
Executing actions inline
The first method you could use to address stale records is to write the necessary code to handle cascading actions in line with the main execution. For example, if you are deleting a recipe using an API, you could extend the route handler to delete the associated ingredients and steps as well.Scheduled jobs
The second approach is using a system that will scan the database at regular intervals for cascading actions that need to be performed. For example, you might set up Cron with a script that will execute queries against the database to find records that are soft-deleted, and run the necessary SQL to delete the ingredients and steps, then the recipe itself. The main action would flag the record in therecipes
table as being soft-deleted:
DELETE
operations are relatively straightforward, addressing UPDATE
operations may be a challenge. There is also an inherent delay where stale records would exist in the database between script executions.
You can see a full example of how to handle this in Rails in our Ruby on Rails: 3 tips for deleting data at scale blog post.