Should I use ON DELETE CASCADE ,: dependent =>: destroy, or both?

In a Rails application, I have external key restrictions in MySQL that I set them manually, separately from my migrations.

I am trying to figure out whether to use the ActiveRecord :dependent => :destroy parameter. For example, in my schema, I have tables ...

 users ----- log_entries ----------- user_id # Has FK constraint to users.id with ON DELETE CASCADE 

And in my model, I could ...

 class User < ActiveRecord::Base has_many :log_entries, :dependent => :destroy end 

Should I leave the dependent option on the model and just leave it in the database? Or is it good to have it there? When deleting things in this application, I do not need to run callbacks. In all cases, simply removing them is enough.

Another factor to consider is that the FK restrictions will not be present in my test environment, probably because rake db:test:prepare does not set them. So it's hard to check what happens if I rely completely on MySQL for cascading deletions.

+2
ruby mysql ruby-on-rails activerecord
source share
3 answers

You should not use depend =>: destroy in your models if you have FK with ON DELETE CASCADE. It can run unnecessary requests, and you cannot count on the fact that this will not break the work in the future. You must put a comment in your model file to document that this is happening. although.

I also recommend doing FK in migrations. It would be much better if your test database had the same limitations as your production database, which could cause very hidden errors. There is a RedHill plugin (redhillonrails_core), which simplifies foreign keys in migration and allows you to reset circuits with FK restrictions, so testing is much simpler.

+6
source share

I would add: depend =>: destroy there simply because it conveys the intention. More importantly, not all databases will support DELETE CASCADE, so the database adapter will be responsible for determining how best to delete related records. In my opinion, it is more important to put it in the model at least. But the right answer is the right answer.

+3
source share

Depends: dependent =>: destroy will load each child model and make callbacks . ON DELETE CASCADE does not make any callbacks, but with lightning speed.

If you want to get rid of models, ON DELETE CASCADE is probably the way to go, or use: depend =>: delete_all, which will only run 1 query instead of N + 1.

+3
source share

All Articles