Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Extends Sinatra with ActiveRecord helper methods and Rake tasks.
Ruby

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib/sinatra
spec
.gitignore
CHANGELOG.md
Gemfile
LICENSE
README.md
Rakefile
sinatra-activerecord.gemspec

README.md

Sinatra ActiveRecord Extension

About

Extends Sinatra with extension methods and Rake tasks for dealing with an SQL database using the ActiveRecord ORM.

Instructions

First, put the gem into your Gemfile (or install it manually):

gem 'sinatra-activerecord'

Also put one of the database adapters into your Gemfile (or install them manually):

  • sqlite3 (SQLite)
  • mysql (MySQL)
  • pg (PostgreSQL)

Now specify the database in your app.rb (let's assume you chose the sqlite3 adapter):

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

set :database, 'sqlite:///foo.db'

Note that in modular Sinatra applications (ones in which you explicitly subclass Sinatra::Base), you will need to manually add the line:

register Sinatra::ActiveRecordExtension

Now require the rake tasks and your app in your Rakefile:

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. Usually models in Sinatra aren't that complex, so you can put them all in one file, for example ./db/models.rb.

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 like this:

if database.table_exists?('users')
  # Do stuff
else
  raise "The table 'users' doesn't exist."
end

Changelog

You can see the changelog here.

History

This gem was made in 2009 by Blake Mizerany, one of the authors of Sinatra.

License

MIT

Something went wrong with that request. Please try again.