# Basic ActiveRecord Usage

**URL:** <https://www.ruby-forum.com/t/basic-activerecord-usage/72108>\
**Category:** Ruby\
**Created:** [October 14, 2006, 6:57am UTC](https://www.ruby-forum.com/t/basic-activerecord-usage/72108 "2006-10-14T06:57:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jotto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/eada6e/32.png) [@jotto](https://www.ruby-forum.com/u/jotto)\
**Post date:** [October 14, 2006, 6:57am UTC](https://www.ruby-forum.com/t/basic-activerecord-usage/72108/1 "2006-10-14T06:57:18Z")

</div>

I want to run a Ruby script outside of Rails and still use Active  
Record. This is what I’m trying but I am getting a “const\_missing”  
error - do I need to reference the connection in the printlisting  
method?:

require ‘rubygems’  
require ‘active\_record’

class TheMode \< ActiveRecord::Base  
def initialize  
end

def printlisting  
ActiveRecord::Base.establish\_connection(:adapter =\> “mysql”, :host =\>  
“localhost”, :username =\> “root”, :password =\> “root”, :database =\>  
“commentstable”)  
listing = Comment.find(:all)  
puts listing.text  
end

temp = TheMode.new  
temp.modemaker

---

<div class="post-metadata">

**Author:** ![jotto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/eada6e/32.png) [@jotto](https://www.ruby-forum.com/u/jotto)\
**Post date:** [October 14, 2006, 7:45am UTC](https://www.ruby-forum.com/t/basic-activerecord-usage/72108/2 "2006-10-14T07:45:19Z")

</div>

On 10/13/06, jotto [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> def initialize  
> temp = TheMode.new  
> temp.modemaker

require ‘comment’

Rails autoloads constants in lib, app/models, etc. When you use Active  
Record on its own, you need to handle that yourself.

Best,  
jeremy

---

<div class="post-metadata">

**Author:** ![jotto](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/eada6e/32.png) [@jotto](https://www.ruby-forum.com/u/jotto)\
**Post date:** [October 14, 2006, 3:04pm UTC](https://www.ruby-forum.com/t/basic-activerecord-usage/72108/3 "2006-10-14T15:04:21Z")

</div>

I found this Wiki article, which helped me out a lot.

[http://wiki.rubyonrails.org/rails/pages/HowToUseActiveRecordOutsideRails](http://wiki.rubyonrails.org/rails/pages/HowToUseActiveRecordOutsideRails)

New to Ruby, but I have a theory. When ever I’ve done this,  
I typically run ActiveRecord::Base.establish\_connection  
outside of any class definition, that seemed to work for me.  
Another approach I’ve used (when some of my models in rails  
connection to a different DB than the rest of the rails app)  
is to have a top level class (called DB) that is something like

class DB \< ActiveRecord::Base  
ActiveRecord::Base.establish\_connection( … )  
end

And then TheMode and Comment would be

class TheMode \< DB  
end

class Comment \< DB  
end

Good luck.

Andy
