March 12, 2012

Rails console: restore data by copying between databases

Okay, this is the 2nd time I've had to do this. So I'm writing this down in the hopes that it will help somebody else but also so that I'll know how to get started in the heat of the moment next time...

Have you ever mistakenly deleted something from your production database? Or needed to copy an object from your staging server to your production server?

The following is a method for moving objects from one database to another in the rails console.

First off, to switch to another database in the console you can use the following command:

Where environment is one of your configured environments (i.e. production, staging, development).

Pretty handy, eh? Now you can connect to your staging environment and read objects from the database then connect your production environment and write them to your production database using something like:

This method is covered in more detail here

That's a pretty good start but it has a couple of problems. Firstly, the objects created are not exact copies they do not preserve the IDs of objects. Also, if (like any good rails programmer!) you use assignment protection this sort of mass assignment will fail.

So I wrote this little function to overcome these obstacles:

To use it do something like:

It uses "send" to bypass the mass assignment checks and sets the ID separately.

Thanks to Just Barebones for this posting that got me going in the right direction:

http://justbarebones.blogspot.com/2007/10/copy-model-data-between-databases.html

Posted by Barry at March 12, 2012 1:14 PM

Leave a comment