Rails quick tips #1: Console sandbox

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
[1] (rails_new) main: 0> User.count
   (17.7ms)  SELECT COUNT(*) FROM "users"
=> 1
[2] (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
=> [#<User id: 1, email: "test@example.com", created_at: "2018-06-26 07:22:18", updated_at: "2018-06-26 07:22:18">]
[3] (rails_new) main: 0> User.count
   (0.3ms)  SELECT COUNT(*) FROM "users"
=> 0
[4] (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.

Free Resources

Attributions:
  1. undefined by undefined