Adding Postgres and ActiveRecord

Set up your application

First set up a basic Sinatra application as outlined in the previous section. Then, add your base routes to it.

get "/" do
  401
end

error 401 do 
  "Not allowed!!!"
end

or better yet, download/use the basic application template from the code samples folder!

Configure your project for a database

Add gems

You’ll need to add a few gems to your project. Add the following to your Gemfile (if they’re not already there!)

gem 'activerecord'
gem 'pg'
gem 'sinatra-activerecord' # excellent gem that ports ActiveRecord for Sinatra
gem 'rake'

Install and update your project gems by typing the following at the command line:

bundle install

Requirements

Now that we have all of the necessary libraries, we need to setup an actual database to store all of our data in.

Require sinatra/activerecord in your project like so, right after the line where you’ve required Sinatra itself:

require "sinatra"
require 'sinatra/activerecord'

Configure the Database

Next, we need to tell Sinatra what kind of database we’ll use and where to find it. We do this with a single line near the top of our main application file.

Create a file called database.yml in a subfolder of your project called config

It should look something like this

development:
  adapter: postgresql
  encoding: unicode
  database: database-name
  pool: 5
  timeout: 5000

test:
  adapter: postgresql
  database: database-test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: ENV['DATABASE_URL']
  pool: 5
  timeout: 5000

You’ll notice that there are three mappings to databases. The first is in your development environment - i.e. your local machine. The second is something called test - this supports the case where you might want to deploy your app to a testing environment to allow users or QA to test your app before you make it live. The third is production or the live instance i.e. what we’ll deploy to heroku.

Each of these definitions will tell our application how to setup the actual database for this project as well as tell Sinatra how to connect to it.

  • Ultimately the heroku instance will have a mapping to the database defined in an environment variable. Don’t edit this!

  • But… For your local machine make sure to replace <databasename> with a better database name that describes the project a little, like employeedirectory or twitter_bot_db.

×

Subscribe

The latest tutorials sent straight to your inbox.