Basic ActiveRecord Usage

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

On 10/13/06, jotto [email protected] 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

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs