Often times in your Rails app, you would run rake tasks to manipulate data in your database.

This could be for updating the attributes for a bunch of rows in table, or even for destroying records.

Let’s look at such an example of a rake task.

Here we are running this rake task to destroy records in a specific table.

Let’s run it:

Let’s make sure the records were actually deleted:

This rake task is simple, but what if we had a more complex use case?

And it dealt with manipulating tons of data?

And you had to run it on … the production database?

Risky, I know.

The Rails console actually provides a nifty way to deal with such cases.

The ‘sandbox’ mode.

Here’s the sandbox mode in action. It makes sure that any database action you do is rolled back when you exit the console.

That’s good, but this is applicable only for the Rails console.

Can we do the same for rake tasks?

Yes. We can!

Since rake or Rails does not give out of the box support for sandbox mode, we will write a container rake task which sets up the sandbox mode for us and will run the rake task of our choice.

If you are wondering where the code from opening and closing a transaction came from, it comes directly from the source code for rails console.

Now that we have the sandbox container rake task ready, let us run the same rake task again in sandbox mode.

Our container task takes in the name of the rake task we want to execute as an argument.

Here’s an example:

Now let us actually make sure that the records were not deleted:

And voila! It works:

So, to run your rake tasks in sandbox mode:

Drop the sandbox.rake file in your Rails project. Execute bin/rake sandbox <name of your rake task> to run your task in sandbox mode. Profit!

How does this help?