Don’t use Rails console sandbox in production
You can use
rails console to gain full access to models and controllers and helpers provided by Rails in an interactive ruby (irb) session.
This is fantastic as it provides us with the ability to quickly do some tests, like creating an instance of
User and an instance of a
Micropost and then trying to associate them by doing something like:
user1 = User.first
mp1 = Micropost.first
user1.micropost = mp1
user1.saveuser1.micropost #=> prints the mp1 instance object
But wait, there’s more! Perhaps you’re doing this while developing a new micropost feature for your app, and you’d like for your testing to not update even your development database because it’s messy. You are, after all, just tinkering to gain an understanding of Rails through trial and error (admit it, we all do this).
There’s a feature in Rails for that, enabled by the
rails console --sandbox
which would create a new console session that tells you you’re in sandbox mode:
Loading development environment in sandbox (Rails 184.108.40.206)
Any modifications you make will be rolled back on exit
I thought this was clear enough.
Well, it was at first. Then I started wondering if I could do this safely in production. Like, you know, SSH into a production server and run
rails console --sandbox and then trial-run a migration or data cleanup before actually running a full migration.
So I did a little googling, and found out that even in sandbox mode, database rows are fully locked, which in real time prevents your live production services from modifying them.
So… moral of the story: don’t use
rails console --sandbox in production and expect good outcomes.
I’ll happily use it in development to test things, but I’ll never run it in a production Rails app.
Frankly it should not take too much effort to recreate a small subset of data in my development database to then tinker with. And there are some other methods for testing if an ActiveRecord object is “saveable” like
user.valid? so you don’t need to run
user.save . This is a whole other topic.
But I think feasibility of taking another approach isn’t the point here — it’s more about how misleading it can be to think that because
--sandbox is passed into the console, that it is safe to play around with production data. Be careful!