delete_all vs destroy_all? [英] delete_all vs 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.
推荐答案
如果你想删除用户和所有相关对象 - > 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 => :destroy VS:dependent => :delete_all
-
destroy
/ -
delete
/delete_all
:所有关联对象都将立即销毁,而不调用他们的:destroy方法
destroy
/destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/delete_all
: All associated objects are destroyed immediately without calling their :destroy method
这篇关于delete_all vs destroy_all?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!