Ruby on Rails
HowToUseActiveRecordThroughStandAloneScript

To use ActiveRecord completely without rails, see HowToUseActiveRecordOutsideRails.

As with everything else in Ruby and Rails, it is pretty easy to use ActiveRecord outside of a web server.

By using the environment file, your script will use whatever database and whatever environment you’ve configured your system for.

Make a new file in the existing /script/ directory or in your own /shellscripts/ directory.


#!/usr/bin/env ruby
RAILS_ENV = 'production'

  1. This does NOT work. I looked back 3 revisions and found the correct line
    #require File.dirname(__FILE__) + ‘/../config/boot’
    require File.dirname(__FILE__) + ‘/../config/environment’
  1. use your models as you would normally
    items = Railsmodel.find(:all)
    items.each do |item|
    begin
    item.do_stuff
    rescue Exception
    puts $!
    end
    end

When you’re done, just run:

ruby recordrunner.rb (or whatever your file name is)