Ruby on Rails
HowToUseActiveRecordOutsideRails

With existing rails application

Include the following in your ruby script


require '/path/to/rails/app/config/environment'

or run the script with script/runner. This can be used as a shell script shebang as well… see APP_ROOT/script/runner -h

Without existing rails application

Create a database manually:

# mkdir db
# sqlite db/database.sqlite
SQLite version 2.8.15
Enter ".help" for instructions
sqlite> CREATE TABLE 'tasks' (
   ...>   'id' INTEGER PRIMARY KEY NOT NULL,
   ...>   'title' VARCHAR(255) DEFAULT NULL
   ...> );

Or use a migration to create the DB:

# require AR
require 'rubygems'
require 'active_record'

# connect to the database (sqlite in this case)
ActiveRecord::Base.establish_connection({
      :adapter => "sqlite", 
      :dbfile => "db/database.sqlite" 
})

# define a migration
class CreateTasks < ActiveRecord::Migration
  def self.up
    create_table :tasks do |t|
      t.string :title
    end
  end

  def self.down
    drop_table :title
  end
end

# run the migration
CreateTasks.migrate(:up)

Then use the following ruby script:

# require AR
require 'rubygems'
require 'active_record'

# connect to the database (sqlite in this case)
ActiveRecord::Base.establish_connection({
      :adapter => "sqlite", 
      :dbfile => "db/database.sqlite" 
})

# define a simple model 
class Task < ActiveRecord::Base
end

Open the IRB and require the file and play around with your new ActiveRecord-enabled database!

irb -r tasks.rb
irb(main):001:0> Task.create "title" => "Item #1" 
irb(main):002:0> Task.create "title" => "Item #2" 
irb(main):003:0> Task.create "title" => "Item #3" 
irb(main):004:0> Task.find(:all).each { |t| puts t.title }
Item #1
Item #2
Item #3