Alex Rivera | Logout

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

Asked 2008-09-15T11:25:19.260
66

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

3 Answers

40

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

answered 2013-02-13T22:01:48.670
3

That Rake task can be provided by the db-populate plugin:

http://github.com/joshknowles/db-populate/tree/master

answered 2008-09-15T21:04:17.930
2

I'd keep it in a migration. While it's recommended to use the schema for initial setups, the reason for that is that it's faster, thus avoiding problems. A single extra migration for the data should be fine.

You could also add the data into the schema file, as it's the same format as migrations. You'd just lose the auto-generation feature.

answered 2008-09-15T11:33:31.813

Your Answer