views:

212

answers:

1

I have a small ruby script in which I'd like to use ActiveRecord to easily access a database model. What is the best way to do it?

+11  A: 
require "rubygems"
require "activerecord"

#Change this to reflect your database settings
ActiveRecord::Base.establish_connection (
  :adapter => "mysql",
  :host => "localhost",
  :username => "root",
  :password => "password",
  :database => "some_database")

#Now define your classes from the database as always
class SomeClass < ActiveRecord::Base
  #blah, blah, blah
end

#Now do stuff with it
some_class = SomeClass.new
some_other_stuff = SomeClass.find :all
Pesto
undefined method `require_gem' - you mean gem "activerecord"?
Daniel Cukier
The require_gem call is deprecated. It should be require "activerecord" now.
kchau
@kchau: Oh, thanks. I haven't used it in quite some time.
Pesto
Another related question: how to have an environment sensible database.yml?
Daniel Cukier