updating your rails app database from the command line

I needed some way of bootstrapping the app with initial data. The quick and dirty trick we had was to have the ActiveRecord commands in some text file, then copy/paste them in the rails console and voila, a database with stuff in it.

Having to manually copy a bunch of ruby code in the console and then run it there was kind of boring and error prone though. However, since we only have to do it once (or so we thought), it was acceptable.

As it turned out we had to do it more than once, so it got old very quickly. And not only it was boring and error prone, the rails console (I think) was dropping characters left and right while pasting our ruby instructions.

So now it was boring, error prone and destructive.

We needed to automate this. We already had the code in some text file, so how hard could it be to simply rename the file something.rb and run it?

Ruby has no idea what ActiveRecord is for example, so the script needs to know that. Simply adding

require File.expand_path(File.dirname(__FILE__) + "/config/environment")

at the top of the file does it. Yay! (the script is at the project root)

Great, now I can run any rails code in my script, like bootstrap the database, and it will just work.

Well, almost. By default rails will use the “development” environment. I’m bootstrapping things in production, not development.

Super easy, before loading the project environment, I need to tell rails that I really want to be in production mode. Add this line before the line that loads the environment.

ENV['RAILS_ENV'] = ‘production’

That’s it, two lines of code and your command line script will be updating the database!

3 Comments »

  1. Henrik N said,

    October 24, 2007 @ 1:43 pm

    Rake is probably a better fit. Add a file like lib/tasks/populate.rake containing:


    namespace :db do
    task :populate => [:environment] do
    User.create!(:name => “Foo”)

    end
    end

    then do rake db:populate.

    Also, “E-mail required)” in your comment form is missing an opening parenthesis. :)

  2. Julio Santos said,

    October 25, 2007 @ 5:05 am

    Henrik, I agree, the rake approach is better. Thanks for the suggestion. Oh and thanks for the parenthesis thing. It should be fixed now :)

  3. bobc said,

    February 15, 2008 @ 9:10 pm

    Thanks, this looks like it will be handy for a cron job to do administrative tasks, such as cleaning up sessions, for example.

RSS feed for comments on this post · TrackBack URI

Leave a Comment