Database Connections with ActiveRecord

For connecting to the database, we’ll use activerecord gem.

Add database configuration to connect to sqlite3

Also add a configuration file database.yml with the connection details and the sqlite3 gem for connecting to the sqlite database. app.rb needs changes to update this configuration.

#changes in app.rb
# ...
require 'sinatra/activerecord'
# ...
class ConferenceApp < Sinatra::Base
set :database_file, 'config/database.yml'
# ...
# ...
end
view raw app_3.rb hosted with ❤ by GitHub

Add Rakefile

Add the rake gem along with the Rakefile. This gives handy rake tasks for creating the table (migrations) and managing them.

# Rakefile
require './app'
require 'sinatra/activerecord/rake'
view raw Rakefile hosted with ❤ by GitHub

bundle exec rake -T will display the added rake tasks.

Create the sqlite database, by running bundle exec rake db:create.

Add a migration and model for Speaker object

Create a migration with the following rake command:

bundle exec rake db:create_migration NAME=create_speakers

Change the created migration file in db/migrate folder, to add the required database fields.

class CreateSpeakers < ActiveRecord::Migration[5.1]
def change
create_table :speakers do |t|
t.string :name, null: false
t.string :twitter_handle
t.text :bio
t.string :talk_title
end
end
end

Run migrations with the rake task bundle exec rake db:migrate

Create a model file for Speaker, to access this table.

# file models/speaker.rb
class Speaker < ActiveRecord::Base
validates :name, presence: true
end
view raw speaker.rb hosted with ❤ by GitHub

I’ve added a basic validation for the model. Read more on activerecord basics in the official basics introduction.

Add the pry gem for debugging and execute the following two statements in the pry console, for adding rows to the speakers table.

Seed Speakers

require './app'

Speaker.create(name: 'John', twitter_handle: 'johnruby',
  bio: 'This is John\'s bio', talk_title: 'How to bootstrap a sinatra application')

Speaker.create(name: 'Jacob', twitter_handle: 'jacob-ruby',
  bio: 'This is Jacob\'s bio', talk_title: 'Introduction to graphql')

Add a /speakers endpoint

Create a new endpoint to show the list of speakers, as JSON.

# Changes to file app.rb
# ...
require 'sinatra/activerecord'
require_relative 'models/speaker'
class ConferenceApp < Sinatra::Base
# ...
get '/speakers' do
@speakers = Speaker.all
json @speakers
end
end
view raw app_4.rb hosted with ❤ by GitHub
Get notified on engineering articles like this

Follow us on twitter @neumeralhq