I have a relational DB (MySQL) at the backend and cool BackboneJS at the frontend. I have several tables (models in BackboneJS jargon) that are interconnected through foreign keys.
PROBLEM
How do I destroy a specific model, such that destruction cascades to all child models?
EXAMPLE
Consider this quick schema:
PERSON
id
name
PHONE_NUMBER
id
person_id
number
EMAIL_ADDRESS
id
person_id
email
Consider that we have a person "Jack" stored in DB with some phone numbers and email addresses. Also, we have BackboneJS models/collections defined for all of the 3 tables and data is loaded into them. A user on the frontend decides to delete records of Jack with a click.
Now here are a few approaches to delete all records of Jack:
APPROACH#1
Call "destroy" on all models of PhoneNumbers and EmailAddresses related to Jack, then call "destroy" on Jack itself.
Problem(s)
- Too many AJAX calls for one action.
- User will have to wait for a lot of time. (More dependants, more time)
- Deletion will be non-transactional. If user closes the browser during, data will be corrupted.
APPROACH#2
Define foreign key relationships at database level, that ensure cascade deletion of PHONE_NUMBERs and EMAIL_ADDRESSes when a PERSON row is deleted. Then "destroy" BackboneJS model for Jack at frontend.
- BackboneJS Models for dependants will never know what happened to their corresponding records in the backend. So they'll remain intact.
APPROACH#3
Create a URL on server side application "/thoroughly-delete-person" (which makes sure to delete a person with all of its dependants) and invoke it from the frontend instead of calling BackboneJS's Model#destroy on Jack.
- Same problem as in Approach#2
So seems like there is no perfect solution for this simple problem. Did you face it too? What approach did you take and why was it better?