How to use ActiveRecord without Rails

This is an example of how to use ActiveRecord without Rails.

app.rb:

require 'active_record'
require 'sqlite3'
require 'logger'

ActiveRecord::Base.logger = Logger.new('debug.log')
configuration = YAML::load(IO.read('config/database.yml'))
ActiveRecord::Base.establish_connection(configuration['development'])

class User < ActiveRecord::Base
end

db/migrate/001_schema.rb

class Schema < ActiveRecord::Migration
  def change
    create_table :users, force: true do |t|
      t.string :name
    end
  end
end

Rakefile:

require './app'

task :default => :migrate

desc "Run migrations"
task :migrate do
  ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end

database.yml:

development:
  adapter: sqlite3
  database: db/data.sqlite3
  pool: 5
  timeout: 5000

Updated 2307 days ago