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.

Add Rakefile

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

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.

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

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

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.

Get notified on engineering articles like this

Follow us on twitter @neumeralhq