As You already started going this putting dependencies between models is a good approach, this will remove everything linked on destroy
(don't mix up with delete
it executes SQL query without Rails callbacks). Though I started to avoid this technique in latest projects.
I am kind of old school about DB cleanliness, so we usually also use gems to enforce FK integrity. It adds another layer of maintenance when deleting objects (as it will throw SQL error when triggered), but I find it more reliable, then a single line in a model. Also we usually overcome this added complexity by providing models with custom_destroy
methods that executes delete
on all dependent objects.
def custom_destroy
self.class.transaction do
child_objects.delete_all
some_other_child_objects.delete_all
delete
end
end
This provides an advantage of speed, because using destroy_all on 10 child objects will execute 10 SQL queries (+ all the callbacks), this method on the other hand will do only one query.
We seldomly have a need to clean up old unneeded data (expired items), we use a rake tasks for that. If You are on Heroku simply use Heroku scheduler, if You are on a VPS/dedicated machine I advice on using whenever gem, it should have a good integration with Capistrano as well.