Search This Blog

November 25, 2011

Rails 3 and its Sandbox


Rails console has always been a friend in need for the Rails developer. More often, we get to the console to try out some coded snippets to verify and validate our assumptions, either while writing the test cases or during the coded implementation. In this process it is very likely that we end up modifying the state of the underlying database. This inturn can cause some headaches or frustration. Nonetheless you soil the database with junk data. If you are fine with it, then read no further - this post is not for you. If however you are wondering for a way to SANDBOX your play environment from soiling the database, then read on.

Run your console with the command as below:
$ rails c --sandbox 
That is all you need to do to maintain the sanity of your undedrlying database.

So what does this sandboxing do? It keeps journaling all the activities that you do on the database and will undo it all upon exit so that the database goes back to the state previous to sandboxing. 

There are some implications however to working this way though. If you were to run the sandbox on say, development database, then you wouldn't be able to run your DB migrations on your database while the --sandbox is on. Oh!, in fact you wouldn't be able to modify the state of the databases in any manner, be it insert / update / delete records. When you attempt to do it, you would see that the DB throws an error message that reads something as below: 
ActiveRecord::StatementInvalid: SQLite3::BusyException: database is locked: ...