本文翻译自: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 ,它没有任何删除我可以看到的内容。
Delete by
id
, 按id
删除,Delete the current object like:
user.remove
, 删除当前对象,如:user.remove
,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 它是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 delete
and delete_all
which won't enforce :before_destroy
and :after_destroy
callbacks or any dependent association options. 或者,您可以使用delete
和delete_all
,它们不会强制执行:before_destroy
和:after_destroy
回调或任何依赖关联选项。
User.delete_all(condition: 'value')
will allow you to delete records without a primary keyUser.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楼
-
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. 如果您使用删除操作,则不会发生回调。
User.destroy
,User.delete
User.destroy
,User.delete
User.destroy_all(<conditions>)
orUser.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
. 有delete
, delete_all
, destroy
和destroy_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
. 通常, delete
比destroy
更快。