Using Migrations to Insert Content

Migrations have made “Rails”:http://www.rubyonrails.org development so much easier by being able to code our SQL “data definations”:http://en.wikipedia.org/wiki/Data_Definition_Language in “Ruby”:http://www.ruby-lang.org. You can also use migrations to code in some data too.

To do this you just access the models as you would in any other “Rails”:http://www.rubyonrails.org file. For example, if you want to add to rows to “Typo’s”:http://typo.leetsoft.com Setting Table you could use this migration.

class MyNewSettings  'new_setting_toggle', :value => 0)
    Setting.create(:name => 'new_setting_url', :value => 'http://www.foo.com')
  end

  def self.down
    Setting.find(:first, :conditions => [ "name IN (?)", 'new_setting_toggle' ] ).destroy
    Setting.find(:first, :conditions => [ "name IN (?)", 'new_setting_url' ]).destroy
  end
end

This would insert a two new rows into Setting with the names and values above. It would also be able to be rolled back using the self.down method.

A great practical example of this would be to initialize the database with some starting values, or even to insert some demo data. The only thing you need to watchout for is that since migrations are sequential, if you have this migration the it will have to be ran if make a migration after it. A workaround is to generate the migration and move the migration file out of db/migrations/. Then you can create a Rake task to run the migration if the user needs demo data (but you will need to fuss with the schema_info table)

Eric Davis