I was talking to someone today who was under the impression that ActiveRecord was tied to Rails and couldn't be used unless you were writing a web application. So here's a sample that shows exactly that.
Put this in a file by itself (I called it sample.rb) and run it from the command line with "ruby sample.rb"
require 'rubygems'
require 'activerecord'
ActiveRecord::Base.establish_connection({
:adapter => 'postgresql',
:database => 'mydatabase',
:username => 'myuserid',
:password => 'mysecret',
:host => 'localhost'
})
class Brand < ActiveRecord::Base
end
Brand.find(:all).each {|b| puts b.domain_name}
Obviously, you have to have a database set up and tables defined and all that. The point is that this little bit of code initializes ActiveRecord, creates an ActiveRecord model and starts calling methods on it. All of this from the standard ruby interpreter with no web server in sight.
The parameters that you pass in are the same values that you would have specified in config/database.yml in rails.
So what if I want multiple models? Just define them all inline.
require 'rubygems'
require 'activerecord'
ActiveRecord::Base.establish_connection({
:adapter => 'postgresql',
:database => 'mydatabase',
:username => 'myuserid',
:password => 'mysecret',
:host => 'localhost'
})
class Brand < ActiveRecord::Base
end
class Account < ActiveRecord::Base
end
Brand.find(:all).each {|b| puts b.domain_name}
And what if I want to use all the ActiveRecord magic like associations and validations? Same thing.
require 'rubygems'
require 'activerecord'
ActiveRecord::Base.establish_connection({
:adapter => 'postgresql',
:database => 'mydatabase',
:username => 'myuserid',
:password => 'mysecret',
:host => 'localhost'
})
class Mailbox < ActiveRecord::Base
end
class User < ActiveRecord::Base
has_many :mailboxes, :dependent => :destroy
has_many :brands, :through => :mailboxes
end
class BillableItem < ActiveRecord::Base
end
class Account < ActiveRecord::Base
end
class Brand < ActiveRecord::Base
belongs_to :account
has_many :mailboxes, :dependent => :destroy
has_many :users, :through => :mailboxes, :order => 'last_name, first_name'
has_many :billable_items
validates_presence_of :domain_name, :business_name
validates_uniqueness_of :domain_name
end
Brand.find(:all).each {|b| puts b.domain_name}