The Power of Rails Console with the --sandbox Option

Rails console is a powerful tool for interacting with your Rails application’s code and database. But what if you want to experiment with changes without affecting your production data? Enter the --sandbox option.

With rails c --sandbox, you can launch the console in a sandboxed environment. Any modifications made during the session are rolled back, keeping your database intact.

This feature is especially useful for testing queries, making temporary changes, or debugging. You can try out new code snippets, experiment with database operations, or run complex queries without the fear of permanently altering your data.

To use the --sandbox option, simply open your terminal, navigate to your Rails project’s directory, and run rails c --sandbox. Now you have a console session where you can freely explore and test without the risk of making irreversible changes.

Let’s see an example of how to use the --sandbox option. After launching the sandbox console, let’s delete an User object, using the following code:

1
$ rails c --sandbox
1
2
3
4
5
6
7
8
9
Loading development environment in sandbox (Rails 6.1.4.1)
Any modifications you make will be rolled back on exit

irb(main):001:0> User.first.destroy
   (0.1ms)  begin transaction
  User Load (0.2ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  User Destroy (0.3ms)  DELETE FROM "users" WHERE "users"."id" = ?  [["id", 1]]
   (2.0ms)  commit transaction
#=> <User id: 1, name: "John", created_at: "2023-05-30 12:00:00", updated_at: "2023-05-30 12:00:00">

The User.first.destroy command will delete the first user from the database. However, when you exit the sandbox console and run the Rails console without the --sandbox flag, you’ll notice that the first user still exists

Remember, once you exit the sandbox console, all modifications made during the session are discarded. If you want to persist any changes, you need to apply them outside the sandbox.

1
irb(main):002:0> exit
1
$ rails c
1
2
3
4
Loading development environment (Rails 6.1.4.1)
irb(main):001:0> User.first
  User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
#=> <User id: 1, name: "John", created_at: "2023-05-30 12:00:00", updated_at: "2023-05-30 12:00:00">

This demonstrates the safety and isolation provided by the --sandbox option. Changes made within the sandbox console do not persist outside of it, ensuring the integrity of your data.