Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does User.destroy_all or User.delete_all do?

I am working on a project that has the following cucumber step:

Given /^no registered users$/ do
  User.delete_all
end

As a new RoR user this looks a little dangerous even though I'd be testing on our development database because our User table has actual data. What is the line of code doing?

Thanks!

like image 709
Goalie Avatar asked Dec 21 '22 21:12

Goalie


2 Answers

delete_all is from activerecord library not from FactoryGirl.

And the difference between these two is :

delete_all(conditions = nil) public

  • Deletes the records matching conditions without instantiating the records first, and hence not calling the destroy method nor invoking callbacks.
  • This is a single SQL DELETE statement that goes straight to the database, much more efficient than destroy_all.
  • Be careful with relations though, in particular :dependent rules defined on associations are not honored.
  • Returns the number of rows affected.

destroy_all(conditions = nil) public

  • Destroys the records matching conditions by instantiating each record and calling its destroy method.
  • Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods).
  • Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).

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 . If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.

like image 160
Vik Avatar answered Jan 04 '23 03:01

Vik


delete_all is not from FactoryGirl, it is an active record command and it deletes the users from your database. If you are running this from cucumber then it should run against your test database, not development.

A better alternative is destroy_all since that version will run any associated callbacks. For example, if users have posts, and you have a before_destroy callback to remove posts if users are deleted.

Here's a link to more info about delete_all

like image 20
Dty Avatar answered Jan 04 '23 04:01

Dty