From ecfb9f44cc3f501638f63b3c55266e0edf314481 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 13 Sep 2021 10:30:03 -0500 Subject: [PATCH] Add Prevent Writes With A Sandboxed Rails Console as a Rails til --- README.md | 3 ++- ...t-writes-with-a-sandboxed-rails-console.md | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 rails/prevent-writes-with-a-sandboxed-rails-console.md diff --git a/README.md b/README.md index 33a3a6e..c50f906 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1150 TILs and counting..._ +_1151 TILs and counting..._ --- @@ -723,6 +723,7 @@ _1150 TILs and counting..._ - [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md) - [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md) - [Pretend Generations](rails/pretend-generations.md) +- [Prevent Writes With A Sandboxed Rails Console](rails/prevent-writes-with-a-sandboxed-rails-console.md) - [Query A Single Value From The Database](rails/query-a-single-value-from-the-database.md) - [Read In Environment-Specific Config Values](rails/read-in-environment-specific-config-values.md) - [Read-Only Models](rails/read-only-models.md) diff --git a/rails/prevent-writes-with-a-sandboxed-rails-console.md b/rails/prevent-writes-with-a-sandboxed-rails-console.md new file mode 100644 index 0000000..c9e8c4e --- /dev/null +++ b/rails/prevent-writes-with-a-sandboxed-rails-console.md @@ -0,0 +1,24 @@ +# Prevent Writes With A Sandboxed Rails Console + +I often open a `rails console` to play around with some data and make sure I +understand how some models can be instantiated while respecting their +associations. There are plenty of times where I've created some data in the +`development` database that doesn't need to be there. It may even be incomplete +data from a failed experiment. + +This data accumlates and clutters up the database. + +One way to avoid this is by running the console in a sandboxed mode. Include +the `--sandbox` flag when starting up a session to do this. + +```bash +$ rails console --sandbox +Loading development environment in sandbox (Rails 5.2.6) +Any modifications you make will be rolled back on exit +[1] pry(main)> +``` + +This wraps the session in a transaction so that any writes to the database can +be rolledback afterward. + +[source](https://dev.to/citizen428/rails-quick-tips-1-console-sandbox-4k0c)