How to use ActiveRecord without Rails

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

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

ActiveRecord::Base.logger = Logger.new('debug.log')
ActiveRecord::Base.configurations = YAML::load(IO.read('database.yml'))
ActiveRecord::Base.establish_connection('development')

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

    add_index :users, :name
  end
end

Schema.new.change

class User < ActiveRecord::Base
end

database.yml:

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

Updated 2245 days ago