Loading Fixtures in a Migration
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.
1require 'active_record/fixtures'
2
3class CreateCategories < ActiveRecord::Migration
4 def self.up
5 create_table :categories do |t|
6 t.column :name, :string
7 end
8
9 Fixtures.create_fixtures('test/fixtures', File.basename("categories.yml", '.*'))
10 end
11
12 def self.down
13 drop_table :categories
14 end
15end
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 guarantee that my fixture data will be loaded for any environment.
Comments
comments powered by Disqus