Ruby: Active Record
Ruby tutorial for setting up a back-end database (sqlite3)
Backend Development is also known as server-side development. It is everything that the users don’t see and contains behind-the-scenes activities that occur when performing any action on a website. It focuses primarily on databases, backend logic, APIs, and Servers.
In this Ruby tutorial I will be walking through an example of how to set-up a back-end database so that the front-end of an app can fetch data. Feel free to code-along if you’d like!
Introduction
In this example, a theater company is holding auditions for their movie roles. An actor may only audition for a single role. This means that a role will have many auditions. The relationship is shown below:
Before we begin doing anything to our code we want to make sure we run bundle install to install any dependencies specific in our Gemfile and ensure our code runs as intended.
Migrations
Next we want to access our audition and role models in our app folder.
Take a look at both the classes and make sure that the first line includes:< ActiveRecord::Base
This will allow you to utilize Active Record to create and modify tables.
Let’s go over what we talked about above and define the relationship between these two classes. The relationship is a one to many, where the theater role is the one, and the actor auditions are the many. Therefore inside of the Audition class, we want to add a line specifying that a single instance of the Audition class object belongs to another single instance of a Role class object.class Audition < ActiveRecord::Base
belongs_to :role
end
Next we want to go ahead and specify that a single Role instance has many Audition instances.class Role < ActiveRecord::Base
has_many :auditions
end
Run the command “rake -T” in your terminal and a long list of rake commands should appear. The one we want to use is “rake db:create_migration”
Noticed how NAME is a parameter that can be passed. Run the commands: bundle exec rake db:create_migration NAME=create_auditionsbundle exec rake db:create_migration NAME=create_roles
Note: If you get an error when trying to run
rakecommands, you may have a newer version of Rake already installed compared to this lesson, causing a conflict. To avoid this error, runbundle exec rake -T. Addingbundle execindicates that you wantraketo run within the context of this lesson's bundle (defined in theGemfile), not the default version ofrakeyou have installed globally on your computer.
Two new files should be generated in db/migrations. Navigate over and make sure that the naming convention is correct.
The inside of the create_auditions file should look like:class CreateAuditions < ActiveRecord::Migration[5.2]
def change
end
end
Get Leo Chen’s stories in your inbox
Join Medium for free to get updates from this writer.
Next we want to fill out both files. Remember that table names are plural, so we are creating an auditions table for the Audition class. After the table name we write a block of code known as a block parameter t, which is a special Active Record migration object that helps add columns to the table.
class CreateAuditions < ActiveRecord::Migration[5.2]
def change
create_table :auditions do |t|
t.string :actor
t.string :location
t.integer :phone
t.boolean :hired
t.integer :role_id
# t.belongs_to :role end
end
Note that because audition belongs to a role, we have to specify in the table a role_id. You could also use t.belongs_to :role instead of t.integer :role_id although both accomplish the same goal. On the left is the data type and on the right we’ve given a name for each column.
class CreateRoles < ActiveRecord::Migration[5.2]
def change
create_table :roles do |t|
t.string :character_name
end
end
endNow that we are done setting up the tables we can run our migration command:bundle exec rake db:migrate
Active Record will use the code in the migrate folder to create a new database file. It will also create a schema.rb file which is used to capture the current state of the database. Our db/schema.rb file should look like:
You can also use this Rake command to check the status of your migrations:bundle exec rake db:migrate:status
You will notice that you also have a new database file called development.sqlite3
If you download the SQLite extension you will be able to access and look at a preview of your database inside your VSCode.
Testing
Now that our database is all set up we can run tests with the command:bundle exec rake console
Note: to exit out of the testing console simply type “exit” and hit enter.
Now that we are inside of the rake console we can check that our classes exist:Audition
Roles
We can also check that the tables have the proper columns:
Audition.column_names
Roles.column_names
Feel free to play around with the Active Record Query interface and create even more instance and class methods within the app/models class files.
You can also play around with the seeds.rb file to create sample seed data.
What’s Next: Sinatra
The next step would be to set up a server so that the front-end can fetch API data from the back-end. To do this we would need to do a couple steps to set up the “rake server” command with controllers and configuring our Rakefile. Here’s a guide on ruby controllers!







