Should I use ON DELETE CASCADE, :dependent => :des

2020-07-22 18:48发布

In a Rails app, I have foreign key constraints in MySQL which I set them all up manually, separate from my migrations.

I'm trying to figure out whether I should use ActiveRecord's :dependent => :destroy option. 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 have...

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

Should I leave out the dependent option on the model and just leave it up to the DB? Or is it good to have that in there? I don't need to run any callbacks when deleting things in this application. In all cases it's OK to simply delete them.

Another factor to consider is that the FK constraints won't be present in my test environment probably because rake db:test:prepare doesn't set them up. So it's hard to test what happens if I'm relying totally on MySQL to cascade deletions.

3条回答
甜甜的少女心
2楼-- · 2020-07-22 18:57

I'd add :dependent => :destroy there simply because it conveys intent. More importantly, not all Databases will support DELETE CASCADE, so the database adapter will be responsible for determining how to best delete the associated records. In my opinion, it is more important to put it in the model at the very least. But putting it in both is the right answer.

查看更多
虎瘦雄心在
3楼-- · 2020-07-22 18:59

Depends. :dependent => :destroy will load each child model and run callbacks. ON DELETE CASCADE doesn't run any callbacks, but is lightning fast.

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

查看更多
迷人小祖宗
4楼-- · 2020-07-22 19:12

You shouldn't use dependent => :destroy in your models if you have FKs with ON DELETE CASCADE. It can run unnecessary queries, and you can't count on it not breaking things in the future. You should put a comment in your model file to document that it's happening. though.

I also recommend doing the FKs in the migrations. It would be much better if your test database had the same constraints as your production database, that can cause very sneaky bugs. There's a RedHill plugin (redhillonrails_core) that makes foreign keys in migrations easy, and enables schema dumps with FK constraints, so testing is much simpler.

查看更多
登录 后发表回答