Simple Way to Populate a Database in Rails

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,, 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.

2 thoughts on “Simple Way to Populate a Database in Rails”

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>