87
loading...
This website collects cookies to deliver better user experience
rake:db:drop
, then rake:db:setup
.#destroy
method. Each object's callbacks are executed (including :dependent
association options). before_remove
, after_remove
, before_destroy
and after_destroy
callbacks.# 1
Person.where(sex: "male").destroy_all # 😂
# 2
class Author < ActiveRecord::Base
has_many :books
end
author.books.size # => 3
author.books
# => [
# #<Book id: 1, name: "Sapiens", author_id: 1>,
# #<Book id: 2, name: "The Artist's Way", author_id: 2>,
# #<Book id: 3, name: "Remote", author_id: 3>
# ]
author.books.destroy_all
author.books.size # => 0
author.books # => []
Book.find(1) # => Couldn't find Book with id=1
Note: Instantiation, callback execution, and deletion of each record can be time consuming when you're removing many records at once. It generates at least one SQL DELETE
query per record (or possibly more, to enforce your callbacks).
delete_all
instead.delete_all
on your model:% rails c
> Book.count
# => 1200
> Book.delete_all
# => 1200
> Book.count
# => 0
#destroy
method nor invoking callbacks. DELETE
statement that goes straight to the database, much more efficient than destroy_all
..delete_all
method does not instantiate any object hence does not provide any callback (before_*
and after_destroy
don't get triggered).:dependent
rules defined on associations are not honored. Returns the number of rows affected.Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
DELETE
statement. before_*
or after_destroy
callbacks, use the destroy_all
method instead.