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
Then 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
app.rb aftewards. Usually
models in Sinatra aren't that complex, so you can put them all in one
file, for example
Now just establish the database connection in your
(let's assume you chose the
sqlite3 adapter), and
require the models if necessary:
# app.rb require 'sinatra' require 'sinatra/activerecord' require './db/models' set :database, 'sqlite:///foo.db'
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.