Topic: Prepopulate DB before running the application

I have the application which should have some data prepopulated before it runs. There are a few options:
- Use normal SQL execution to populate the DB
- Use something in Rails (e.g. migrations - if possible) to do this
- Use special Rake tasks for this
- Create the missing data in the application when necessary (lazily).

For example, one of the things is the set of roles for authorization. I need a table 'roles' with rows for 'admin', 'user' and 'guest'. What would be the best way to do this? If you had a similar problem, what did you do? The greatest problem obviously is making everything work so automated systems (e.g. Capistrano) can deploy it in a correct state - this is not necessary for the last of the above options, of course. If you have a link to some explanations about this, this is also welcome.

Merry Christmas to all of you celebrating it!

Re: Prepopulate DB before running the application

I use migrations with fixtures for this. Here's an example of a migration (note: I'm using ActiveRecord outside of Rails, so you're fixtures_directory may be different):

require 'active_record/fixtures'
class Programmer < ActiveRecord::Migration
  def self.up
    create_table :programmers do |t|
      t.column :name, :string
      t.column :email, :string
    Fixtures.create_fixtures('./fixtures', 'programmers', 'programmer')
  def self.down
    drop_table :programmers

Here's what the create_fixtures method is expecting:
create_fixtures(fixtures_directory, table_names, class_names = {})

Here's an example of my ./fixtures/programmers.yml fixture file:
  id:    1
  name:  arymcdo

Here's where I learned how to do this (also has other methods): … migrations

hope it helps

Re: Prepopulate DB before running the application

I just figured this out - the migration file and the model class must have the same name:

  class Programmer < ActiveRecord::Migration
  class CreateProgrammers < ActiveRecord::Migration

also, if you're using rails then maybe you can omit this line?

require 'active_record/fixtures'

Last edited by arymcdo (2007-12-28 19:54:29)