A A

Simple Way to Populate a Database in Rails

Tue, Mar 18, 2008

Ruby on Rails, SQL

This is how I populate my database when I have a lot of data but can’t be bothered to write more than a quick throw-away hack. This doesn’t use fixtures, nor migrations (nothing wrong with them, I wuv migrations). Just a ruby file and the Rails console (this is optional actually).

I create a new rb file in lib/ (you can put your files in a sub-directory or anywhere ‘load’ can find them), then write the data I want inserted into the database in a new function in that file. I do so exactly as I would insert data in Rails. Model.create, Model.new, etc…

I then get into the Rails console (ruby script/console) and do load ‘file.rb’ and simply call the function. The database used will vary according to the environment you’re in (test, development, etc). Using ‘load’ every time you call your function(s) is preferred. Load will keep reloading the file (as opposed to ‘require’ which only reads a file once), staying up to date with edits you’re making to the file. For example, in the console:

>> load ‘funk.rb’; add_default_settings

(funk.rb is in /lib/ and add_default_settings is a function in that file)

As of 2.x, Rails now has rake db:migrate:reset and db:migrate:redo, which sends you down one migration and then back up to the current migration (or you can decide how many hops to take back using STEP=n). This is great, especially for tasks like populating a database.

So why don’t I use migrations? I do, but sometimes, especially in a proof-of-concept or throw-away app, I find it faster to skip the proper methods and write up a quick function. If you think that’s bad, you should see my lingering Python addiction. Sometimes I catch myself metaprogramming Ruby code in Python.
Add me. I'm lonely Why not subscribe to the feed?. If you’re on a mobile device I suggest Viigo

Sharing is Caring:
  • del.icio.us
  • Reddit
  • Facebook
  • Mixx
  • Digg
  • Google Bookmarks

2 Comments For This Post

  1. moreno Says:

    Can you please provide a small example where you explain step by step how to populate a db. Thanks cheers moreno

  2. admin Says:

    morena, see this newer post:
    http://biodegradablegeek.com/2008/07/how-to-use-fixtures-to-populate-your-database-in-rails/

Leave a Reply