Sinatra, ActiveRecord, and MySQL

September 6, 2012

If you want to use ActiveRecord with Sinatra, the sinatra-activerecord gem is the way to go. The examples in their documentation are for the sqlite3 adapter. I thought it'd be helpful to show how I used this gem with MySQL instead. I created a models folder in my app root, where I store my ActiveRecord models. You can include all of them in one file (like models.rb) or give each model it's own file, and include it explicitly. We'll use the former for this example.

# config/database.yml
database: dbFoo
username: db_user
password: db_pass
host: localhost
port: 9999

Now we tell the gem about our db settings:

# app.rb
require 'sinatra'
require 'sinatra/activerecord'
require 'yaml'
require './models/models.rb'

DB_CONFIG = YAML::load(File.open('config/database.yml'))

set :database, "mysql://#{DB_CONFIG['username']}:#{DB_CONFIG['password']}@#{DB_CONFIG['host']}:#{DB_CONFIG['port']}/#{DB_CONFIG['database']}"

get '/' do
  @items = Item.all
  erb :index
end

Simple, and you get all the power of ActiveRecord as well as the ability to run migrations.

See Also

Sinatra

sinatra-activerecord