如何删除 ActiveRecord 对象? [英] How do you delete an ActiveRecord object?

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

问题描述

如何删除 ActiveRecord 对象?

How do you delete an ActiveRecord object?

我查看了 Active Record Querying 并且它没有任何我可以看到的删除内容.

I looked at Active Record Querying and it does not have anything on deleting that I can see.

  1. 通过id

删除当前对象,如:user.remove,

你能根据 where 子句删除吗?

Can you delete based on a where clause?

推荐答案

destroydestroy_all 方法,比如

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

或者,您可以使用 deletedelete_all,它们不会强制执行 :before_destroy:after_destroy 回调或任何依赖关联选项.

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') 将允许您删除记录没有主键

User.delete_all(condition: 'value') will allow you to delete records without a primary key

注意:根据@hammady 的评论,如果 User 模型没有主键,user.destroy 将不起作用.

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

注意 2:根据@pavel-chuchuva 的评论,带有条件的 destroy_all 和带有条件的 delete_all 在 Rails 5.1 中已被弃用 - 请参阅指南.rubyonrails.org/5_1_release_notes.html

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

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

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