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

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? :)

Solution 1:

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.

Solution 2:

Use db/seed.rb found in every Rails application.

While some answers given above from 2008 can work well, they are pretty outdated and they are not really Rails convention anymore.

Populating initial data into database should be done with db/seed.rb file.

It's just works like a Ruby file.

In order to create and save an object, you can do something like :

User.create(:username => "moot", :description => "king of /b/")

Once you have this file ready, you can do following

rake db:migrate

rake db:seed

Or in one step

rake db:setup

Your database should be populated with whichever objects you wanted to create in seed.rb