Skip to content

Instantly share code, notes, and snippets.

@ajw725
Last active February 10, 2016 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajw725/103d0ceacb1048cd9faa to your computer and use it in GitHub Desktop.
Save ajw725/103d0ceacb1048cd9faa to your computer and use it in GitHub Desktop.
using ActiveRecord without Rails

There are plenty of tips out there for using ActiveRecord without Rails, but I was having trouble synthesizing all of the relevant information. Once I got things working, I decided to bring together all of the important pieces I used.

Steps, for an imaginary app called MyApp:

  1. Make directories

     mkdir myapp
     mkdir myapp/lib
     mkdir myapp/db
     mkdir myapp/config
    
  2. Create Gemfile

  • bundle init
  • edit accordingly, making sure to include the gems listed in the Gemfile
  • bundle install
  1. Create Rakefile as shown below
  2. Create your database
  • rake db:create
  1. Create your migration(s) using the syntax described here

     rake db:new_migration name=CreateUsers options="attr_1:type attr_2:type attr_3:type"
     rake db:migrate
    
  2. Create your models

  • touch lib/models/<model_name>.rb
  • be sure to inherit from ActiveRecord, e.g. class User < ActiveRecord::Base
  1. Make sure to require the environment.rb file in whatever script you initiate
  2. You're good to go!

Sources:

# default source for active_record_migrations. put this in <app_root>/db/
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000
# configures app environment. put this in <app_root>/config/
# your app should require this file before any other code, so
# require it on the first line of the first script that runs.
require 'bundler/setup'
require 'yaml'
require 'active_record'
# assumes config file is in <app_root>/db/config.yml, as required by active_record_migrations
db_config = YAML.load_file( 'db/config.yml' )[ <your_app_env> ]
ActiveRecord::Base.establish_connection( db_config )
# load all models, assuming they're in <app_root>/lib/models
Dir.glob( 'lib/*' ).each do |folder|
Dir.glob( folder + '/*.rb' ).each do |file|
require_relative "../#{file}"
end
source 'https://rubygems.org'
ruby '2.2.0'
gem 'activerecord', '~> 4.2', '>= 4.2.5.1'
gem 'rake'
gem 'sqlite3'
gem 'active_record_migrations' # access to rake tasks and migrations
require 'active_record_migrations'
ActiveRecordMigrations.load_tasks # load rake tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment