This is the first in a series of Ruby on Rails related quick tips I’m going to publish over the next few days/weeks.
If I had to name the most underused tool in most Rails developer’s toolboxes,
rails console --sandbox would be my choice. Here’s what the documentation has to say on it:
If you wish to test out some code without changing any data, you can do that by invoking
rails console --sandbox.
Here’s an example sandbox console session:
→ rails c --sandbox Loading development environment in sandbox (Rails 5.2.0) Any modifications you make will be rolled back on exit  (rails_new) main: 0> User.count (17.7ms) SELECT COUNT(*) FROM "users" => 1  (rails_new) main: 0> User.destroy_all User Load (0.4ms) SELECT "users".* FROM "users" (1.5ms) SAVEPOINT active_record_1 User Destroy (7.4ms) DELETE FROM "users" WHERE "users"."id" = $1 [["id", 1]] (0.7ms) RELEASE SAVEPOINT active_record_1 => [#
]  (rails_new) main: 0> User.count (0.3ms) SELECT COUNT(*) FROM "users" => 0  (rails_new) main: 0> (0.8ms) ROLLBACK
As can be seen above the last SQL command executed in this console session was
ROLLBACK, so we’re leaving everything just the way we originally found it.
That’s it for today, I’ll be back with another database related Rails quick tip soon.