Sinatra ActiveRecord Extension
First, put the gem into your
Gemfile (or install it manually):
Also put one of the database adapters into your
Gemfile (or install
Now specify the database in your
(let's assume you chose the
# app.rb require 'sinatra' require 'sinatra/activerecord' set :database, 'sqlite3:///foo.db'
Note that the database URL here has 3 slashes. This is the difference from <= 1.0.0 versions, where it was typed with 2 slashes.
Note that in modular Sinatra applications (ones in which you explicitly
Sinatra::Base), you will need to manually add the line:
Now require the rake tasks and your app in your
require 'sinatra/activerecord/rake' require './app'
In the Terminal test that it works:
$ rake -T rake db:create_migration # create an ActiveRecord migration in ./db/migrate rake db:migrate # migrate your database
Now you can create a migration:
$ rake db:create_migration NAME=create_users
This will create a migration file in the
./db/migrate folder, ready for editing.
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.string :name end end def down drop_table :users end end
After you've written the migration, migrate the database:
$ rake db:migrate
You can then also write the model:
class User < ActiveRecord::Base validates_presence_of :name end
You can put the models anywhere. It's probably best to put them in an
external file, and require them in your
models in Sinatra aren't that complex, so you can put them all in one
file, for example
Now everything just works:
get '/users' do @users = User.all erb :index end get '/users/:id' do @user = User.find(params[:id]) erb :show end
A nice thing is that the
ActiveRecord::Base class is available to
you through the
database variable. This means that you can write something
if database.table_exists?('users') # Do stuff else raise "The table 'users' doesn't exist." end
You can see the changelog here.
This gem was made in 2009 by Blake Mizerany, one of the authors of Sinatra.
You can follow me on Twitter, I'm @m_janko.