Ruby-on-rails 如何删除 ActiveRecord 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4177686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you delete an ActiveRecord object?
提问by Blankman
How do you delete an ActiveRecord object?
如何删除 ActiveRecord 对象?
I looked at Active Record Queryingand it does not have anything on deleting that I can see.
我查看了Active Record Querying,它没有任何我可以看到的删除内容。
Delete by
id,Delete the current object like:
user.remove,Can you delete based on a
whereclause?
删除
id,删除当前对象,如:
user.remove,您可以根据
where子句删除吗?
回答by Marek Sapota
It's destroyand destroy_allmethods, like
它destroy和destroy_all方法,比如
user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)
Alternatively you can use deleteand delete_allwhich won't enforce :before_destroyand :after_destroycallbacks or any dependent association options.
或者,您可以使用deleteand delete_all,它不会强制执行:before_destroy和:after_destroy回调或任何相关的关联选项。
User.delete_all(condition: 'value')will allow you to delete records without a primary key
User.delete_all(condition: 'value')将允许您删除没有主键的记录
Note: from @hammady's comment, user.destroywon't work if User model has no primary key.
注意:来自@hammady 的评论,user.destroy如果用户模型没有主键,则不起作用。
Note 2: From @pavel-chuchuva's comment, destroy_allwith conditions and delete_allwith conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html
注 2:来自@pavel-chuchuva 的评论,Rails 5.1 中不推荐使用destroy_all条件和delete_all条件 - 请参阅 guides.rubyonrails.org/5_1_release_notes.html
回答by nonopolarity
There is delete, delete_all, destroy, and destroy_all.
有delete,delete_all,destroy,和destroy_all。
The docs are: older docsand Rails 3.0.0 docs
文档是:旧文档和Rails 3.0.0 文档
deletedoesn't instantiate the objects, while destroydoes. In general, deleteis faster than destroy.
delete不会实例化对象,而destroy会。一般来说,delete比 快destroy。
回答by Tadas T
User.destroy
User.destroy
User.destroy(1)will delete user with id == 1and :before_destroyand :after_destroycallbacks occur. For example if you have associated records
User.destroy(1)将删除用户与id == 1和:before_destroy和:after_destroy出现回调。例如,如果您有关联的记录
has_many :addresses, :dependent => :destroy
After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.
用户被销毁后,他的地址也将被销毁。如果您改用删除操作,则不会发生回调。
User.destroy,User.deleteUser.destroy_all(<conditions>)orUser.delete_all(<conditions>)
User.destroy,User.deleteUser.destroy_all(<conditions>)或者User.delete_all(<conditions>)
Notice: User is a class and user is an instance object
注意:用户是一个类,用户是一个实例对象

