Ruby Findings

digging for gems

Using Active Record from outside of Rails

Posted by Art Green Sun, 14 Oct 2007 16:26:00 GMT

I’ve read a bunch of conflicting advice on how to use active record models defined in a Rails application from outside Rails.

The following is the result of experimenting with others’ advice plus my own digging around:

require 'rubygems'
require 'active_record'
require '/path/to/rails/config/environment'

This should allow you to use your Rails models just like you would in a Rails controller:

#!/usr/local/bin/ruby

require 'rubygems'
require 'active_record'
require '/var/www/railsapp/config/environment'

m = MyModel.new
m.find_all.each { |row|
  puts row.some_column
}

Posted in , | 1 comment | Tags | atom

Trackbacks

Use the following link to trackback from your own site:
http://www.rubyfindings.com/trackbacks?article_id=using-active-record-from-outside-of-rails&day=14&month=10&year=2007

Comments

Leave a response

  1. rabbashanks
    2 months later:
    This doesn't work if your rails app is not using the latest version of rails on your server - eg if your environment.rb file contains the line RAILS_GEM_VERSION = '1.2.6' unless defined? RAILS_GEM_VERSION and your server has both the Rails 1.2.6 and Rails 2.0.2 gems installed, then requiring active_record will pull in version 2.0.2, and requiring your environment.rb file will try to load 1.2.6 and fall over. I think you can just omit the require 'active_record' altogether and let environment.rb handle it.

Leave a comment


html>