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
    end
    Fixtures.create_fixtures('./fixtures', 'programmers', 'programmer')
  end
  def self.down
    drop_table :programmers
  end
end

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:
arymcdo:
  id:    1
  name:  arymcdo
  email: arymcdo@somewhere.com

Here's where I learned how to do this (also has other methods):
http://blog.zmok.net/articles/2007/05/2 … 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:

example:
  003_programmer.rb
  class Programmer < ActiveRecord::Migration
or:
  003_create_programmers.rb
  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)