delete_all 与 destroy_all? [英] delete_all vs destroy_all?

查看:12
本文介绍了delete_all 与 destroy_all?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从表中删除记录的最佳方法.例如,我有一个用户,其用户 ID 跨多个表.我想删除该用户以及所有表中包含其 ID 的所有记录.

I am looking for the best approach to delete records from a table. For instance, I have a user whose user ID is across many tables. I want to delete this user and every record that has his ID in all tables.

u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
u.sources.destroy_all
u.user_stats.destroy_all
u.delete

这有效并从所有表中删除了用户的所有引用,但我听说destroy_all 处理过程非常繁重,所以我尝试了delete_all.它只从他自己的用户表中删除用户,并且所有其他表中的 id 都为空,但保留其中的记录完好无损.有人可以分享执行此类任务的正确流程是什么吗?

This works and removes all references of the user from all tables, but I heard that destroy_all was very process heavy, so I tried delete_all. It only removes the user from his own user table and the id from all the other tables are made null, but leaves the records intact in them. Can someone share what the correct process is for performing a task like this?

我看到 destroy_all 对所有关联的对象调用了 destroy 函数,但我只想确认正确的方法.

I see that destroy_all calls the destroy function on all associated objects but I just want to confirm the correct approach.

推荐答案

你说得对.如果要删除 User 和所有关联的对象 -> destroy_all但是,如果您只想删除用户而不抑制所有关联对象 -> delete_all

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all

根据这篇文章:Rails :dependent =>:摧毁 VS :依赖 =>:delete_all

  • destroy/destroy_all:关联的对象通过调用它们的destroy方法与这个对象一起被销毁
  • delete/delete_all:立即销毁所有关联的对象,而不调用它们的 :destroy 方法
  • destroy / destroy_all: The associated objects are destroyed alongside this object by calling their destroy method
  • delete / delete_all: All associated objects are destroyed immediately without calling their :destroy method

这篇关于delete_all 与 destroy_all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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