Rails 2.3.4 brought with it a simple addition to the platform: seeds. These are the records you want to deploy with your application – you know, not test data, not user data, but the rows that you’ll always need to get the app up and rolling.
The implementation is not particularly exciting, some people have even suggested that it is substantially lacking. But it makes me happy because it gives us a standardized place to keep seed data. No more squirreling data away in migrations, no custom rake tasks, and no plugins (which sound okay, but I haven’t tried).
But, as with many apps, I’ve been developing with data in a table for some time. Having to copy-paste all that stuff into ‘create’ statements would be something of a pain. So, I present to you the complement to db:seed: db_cull. It’s a rake task that, given a particular table, grabs each entry from the database and creates a corresponding line in the seeds file. Simple!
There are two good ways to install this task (sadly, using gems is not possible for rake tasks).
- Install as a plugin:
script/plugin install git://github.com/mikldt/db_cull.git
- Or just copy the rake task into your tasks directory (one-liner):
wget http://github.com/mikldt/db_cull/raw/master/tasks/db_cull_tasks.rake -O lib/tasks/db_cull_tasks.rake
Now, if you have the task, and you have the data in your table (say, ‘Person’) looking the way you want to preserve it in seeds, just run
rake db:cull[person]. Repeat for any tables with seed data, and of course you can edit db/seeds.rb as you see fit.
Once you’ve culled the data, you’re all set to make use of the seeds. If you’re new to seeds, you can take a look at db/seeds.rb. It’s really just a script with a bunch of create statements. Running them is simple:
- For a new deployment, the magical command
rake db:setupwill create your database, run all of your migrations, and pull in the seeds.
- To simply add the seeds to your already migrated database, run
As with any Rails rake command, just stick
RAILS_ENV=production on the end of your
rake db:seed or
rake db:cull to change the environment.
Buyer beware: this task copies over all data besides the primary key. If your seed data includes lots of referential situations, well, the foreign key references will be copied over as-is. In a perfect world, this might be alright (e.g., referencing only one entry), but if referential integrity is important you may want to go with another solution or manually beef up of db/seeds.rb.
Code and documentation are on the github page.