我是否应该使用ON DELETE CASCADE,:depend => :destroy,还是两者皆有? [英] Should I use ON DELETE CASCADE, :dependent => :destroy, or both?

查看:61
本文介绍了我是否应该使用ON DELETE CASCADE,:depend => :destroy,还是两者皆有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails应用中,我在MySQL中具有外键约束,因此我将它们全部手动设置,与迁移无关.

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

我正在尝试确定是否应该使用ActiveRecord的:dependent => :destroy选项.例如,在我的架构中,我有表...

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.

要考虑的另一个因素是FK约束不会出现在我的测试环境中,可能是因为rake db:test:prepare没有设置它们.因此,很难测试如果我完全依赖MySQL来级联删除操作会发生什么情况.

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.

推荐答案

如果您的FK带有ON DELETE CASCADE,则不应在模型中使用dependent =>:destroy.它可以运行不必要的查询,并且您不能指望它将来不会破坏事情.您应该在模型文件中添加注释,以记录正在发生的情况.但是.

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.

我还建议在迁移中进行FK.如果您的测试数据库与生产数据库具有相同的约束,那会导致非常卑鄙的错误,那就更好了.有一个RedHill插件(redhillonrails_core),可以轻松进行迁移中的外键,并启用具有FK约束的模式转储,因此测试要简单得多.

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.

这篇关于我是否应该使用ON DELETE CASCADE,:depend =&gt; :destroy,还是两者皆有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆