你如何删除ActiveRecord对象?

本文翻译自:How do you delete an ActiveRecord object?

How do you delete an ActiveRecord object? 你如何删除ActiveRecord对象?

I looked at Active Record Querying and it does not have anything on deleting that I can see. 我查看了Active Record Querying ,它没有任何删除我可以看到的内容。

  1. Delete by id , id删除,

  2. Delete the current object like: user.remove , 删除当前对象,如: user.remove

  3. Can you delete based on a where clause? 你能根据where子句删除吗?


#1楼

参考:https://stackoom.com/question/HWo2/你如何删除ActiveRecord对象


#2楼

It's destroy and destroy_all methods, like 它是destroydestroy_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 delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options. 或者,您可以使用deletedelete_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.destroy won't work if User model has no primary key. 注意 :从@ hammady的注释中,如果User模型没有主键, user.destroy将不起作用。

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 注2 :从@ pavel-chuchuva的注释中,带有条件的destroy_all和带有条件的delete_all在Rails 5.1中已被弃用 - 请参阅guides.rubyonrails.org/5_1_release_notes.html


#3楼

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. User.destroy(1)将删除id == 1:before_destroy并且:after_destroy回调发生的用户。 For example if you have associated records 例如,如果您有关联的记录

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. 如果您使用删除操作,则不会发生回调。

  1. User.destroy , User.delete User.destroyUser.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>) User.destroy_all(<conditions>)User.delete_all(<conditions>)

Notice : User is a class and user is an instance object 注意 :User是一个类,user是一个实例对象


#4楼

There is delete , delete_all , destroy , and destroy_all . deletedelete_alldestroydestroy_all

The docs are: older docs and Rails 3.0.0 docs 文档是: 较旧的文档Rails 3.0.0文档

delete doesn't instantiate the objects, while destroy does. delete不会实例化对象,而destroy则会实例化。 In general, delete is faster than destroy . 通常, deletedestroy更快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值