I love migrations. I think they are one of the best things about rails. I love that I can count on any changes I’ve done in the database to be consistent across all other databases that I use. Love it.
Sometimes I find that I want pre-load my database with some data, like categories that I have. For testing purposes, I have already created this data in my fixture; now I just want to load that fixture into my database from a migration call.
I know that there is a rake task for this, so I looked into that code and came up with a little something.
require 'active_record/fixtures'
class CreateCategories < ActiveRecord::Migration
def self.up
create_table :categories do |t|
t.column :name, :string
end
Fixtures.create_fixtures('test/fixtures', File.basename("categories.yml", '.*'))
end
def self.down
drop_table :categories
end
end
First I had to require active_record/fixtures. This allows me to call the Fixtures#create_fixtures method, which load my data. Now I can gaurantee that my fixture data will be loaded for any environment.
October 22nd, 2006 at 7:15 pm #Tim Connor
Thanks for the idea. This is also helpful for testing a plugin by loading fixtures, so I gave you a shout-out.
February 4th, 2007 at 1:30 pm #Attila
You gave me a big idea! I have a rich interface manage my data. I use a rake script to extract everything into fixtures. And with your idea, i can put back that data into my database for testing or for initial setup. Cool! Thanks a lot!
May 10th, 2007 at 8:23 pm #Mario Jauvin
I was looking to do exactly this and your example showed me the way. Thanks a bunch.
July 7th, 2007 at 2:18 pm #Phrogz
Why
File.basename( "foo.yml", '.*' )? That just produces"foo", right?. Why not type"foo"directly and save some precious keystrokes and method calls?August 12th, 2007 at 8:43 am #K. Adam Christensen
@Phrogz: I have no Idea what I did that. You are correct in that I should just done that.
Thanks for catching that