如何删除 ActiveRecord 对象?
How do you delete an ActiveRecord object?
I looked at Active Record Querying and it does not have anything on deleting that I can see.
Delete by
id
,Delete the current object like:
user.remove
,Can you delete based on a
where
clause?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它是
destroy
和destroy_all
方法,例如您也可以使用
delete
和delete_all
,它们不会强制执行:before_destroy
和:after_destroy
回调或任何依赖关联选项。注意:根据@hammady的评论,如果用户模型没有主键,
user.destroy
将不起作用。注释 2:根据 @pavel-chuchuva 的评论,带条件的
destroy_all
和带条件的delete_all
已在 Rails 5.1 中弃用 - 请参阅guides.rubyonrails。 org/5_1_release_notes.htmlIt's
destroy
anddestroy_all
methods, likeAlternatively you can use
delete
anddelete_all
which won't enforce:before_destroy
and:after_destroy
callbacks or any dependent association options.Note: from @hammady's comment,
user.destroy
won't work if User model has no primary key.Note 2: From @pavel-chuchuva's comment,
destroy_all
with conditions anddelete_all
with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html有
delete
、delete_all
、destroy
和destroy_all
。这些文档是:旧文档和Rails 3.0.0 docs
delete
不会实例化对象,而destroy
则这样做。一般来说,delete
比destroy
更快。There is
delete
,delete_all
,destroy
, anddestroy_all
.The docs are: older docs and Rails 3.0.0 docs
delete
doesn't instantiate the objects, whiledestroy
does. In general,delete
is faster thandestroy
.User.destroy
User.destroy(1)
将删除具有id == 1
和:before_destroy
和 < code>:after_destroy 回调发生。例如,如果您有关联的记录,则在用户被销毁后,他的地址也将被销毁。
如果您改用删除操作,则不会发生回调。
User.destroy
、User.delete
User.destroy_all()
或User.delete_all()
注意:User 是一个类,user 是一个实例对象
User.destroy
User.destroy(1)
will delete user withid == 1
and:before_destroy
and:after_destroy
callbacks occur. For example if you have associated recordsAfter 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_all(<conditions>)
orUser.delete_all(<conditions>)
Notice: User is a class and user is an instance object
如果您使用 Rails 5 及更高版本,以下解决方案将起作用。
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:删除_全部
If you are using Rails 5 and above, the following solution will work.
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all
从特定表中删除一行或从表中删除记录集非常简单,您所需要做的就是从控制台中通过其 ID 获取记录集,然后删除或销毁它。
Deleting a row from a particular table or a record set from a table is pretty simple, from your console all you need to do is grab the record set by its Id then delete or destroy it.