Thursday, August 28, 2008

Load Sample Data into Dev Database

I needed to load the same type of data into my rails app and then mess around with it to see if my changes broke anything, and the reset the data easily to a standard data set.

Originally I was using the rake command:

rake db:fixtures:load

which loads all of the fixtures you currently have in /test/fixtures.  This works okay, except the test fixtures that I have in that directory are specifically written for unit tests and don't always have the all the fields filled out because I'm only testing certain things.

Basically what I was trying to do was create some fixtures somewhere else that would hold real data that I could populate to my website, try out new migrations and different things on the site and then be able to refresh back to the start after manipulating the database via my website.

I also tried making a data-only migration, which works, but I didn't want to really do it that way, because the data is only for my dev environment.

So what I ended up doing was something similar to what I found here:

I created a custom rake command under /lib/tasks (if there isn't a file there already, create one called "database.rake")

Then in the file add the following code:

namespace :db do
desc "Load sample data fixtures (from db/fixtures) into the development environment's database."
task :sample => :environment do
if RAILS_ENV == 'development'
require 'active_record/fixtures'
Dir.glob(RAILS_ROOT + '/db/fixtures/*.yml').each do |file|
Fixtures.create_fixtures('db/fixtures', File.basename(file, '.*'))
puts "You cannot run this from the production environment."

The basic changes from the Quoted-Printable article that I made was to add the check for the development environment, as you wouldn't want to accidentally run this from your production server and overwrite your database with your sample data.

Now create a directory in /db called fixtures add all your .yml files for each of your models into the /db/fixtures directory and every time you need to refresh your development database to your sample data, simply run the following rake command:
rake db:sample

Pretty cool, huh?

No comments: