How (and whether) to populate rails application with initial data

Luke Halliwell picture Luke Halliwell · Sep 15, 2008 · Viewed 34.2k times · Source

I've got a rails application where users have to log in. Therefore in order for the application to be usable, there must be one initial user in the system for the first person to log in with (they can then create subsequent users). Up to now I've used a migration to add a special user to the database.

After asking this question, it seems that I should be using db:schema:load, rather than running the migrations, to set up fresh databases on new development machines. Unfortunately, this doesn't seem to include the migrations which insert data, only those which set up tables, keys etc.

My question is, what's the best way to handle this situation:

  1. Is there a way to get d:s:l to include data-insertion migrations?
  2. Should I not be using migrations at all to insert data this way?
  3. Should I not be pre-populating the database with data at all? Should I update the application code so that it handles the case where there are no users gracefully, and lets an initial user account be created live from within the application?
  4. Any other options? :)

Answer

Aaron Wheeler picture Aaron Wheeler · Sep 15, 2008

Try a rake task. For example:

  1. Create the file /lib/tasks/bootstrap.rake
  2. In the file, add a task to create your default user:

    namespace :bootstrap do
      desc "Add the default user"
      task :default_user => :environment do
        User.create( :name => 'default', :password => 'password' )
      end

      desc "Create the default comment"
      task :default_comment => :environment do
        Comment.create( :title => 'Title', :body => 'First post!' )
      end

      desc "Run all bootstrapping tasks"
      task :all => [:default_user, :default_comment]
    end
  1. Then, when you're setting up your app for the first time, you can do rake db:migrate OR rake db:schema:load, and then do rake bootstrap:all.