Preliminary Data with Migrations in Rails

At one time or another, you will most likely want your application to set-up with some preliminary data. One common example is a settings or options table within your database, or a default admin user that will be created upon install.

To get this done, is actually a lot easier then you may think..

Simply create a new migration such as:

script/generate migration add_default_user

Now all you need to do is add the data into the migration.

class AddDefaultUser < ActiveRecord::Migration
  def self.up
      User.create(
        :username => 'default', 
        :password => 'password'
       )
  end
 
  def self.down
  end
end

Once you have your migrations the way you like just run

rake db:migrate

to finish the job.

One thing to consider is deleting any records you have added to this migration in the self.down method, depending on your applications requirements. However, I think that this may also be accomplished when the (user) migration is removed.

Posted on September 28, 2008 at 8:20 pm

No Responses »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

(required)

(required)