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

人走茶凉 提交于 2020-01-13 05:28:06

问题


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.


回答1:


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.




回答2:


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:


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.



来源:https://stackoverflow.com/questions/1189970/should-i-use-on-delete-cascade-dependent-destroy-or-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!