In this blogpost let's go step by step and build your own Sinatra API backend that uses Active Record to access and persist data in a database
ActiveRecord and Sinatra
ActiveRecord can be used in conjunction with Sinatra to handle creating the data tables used to store the data being asked for by HTTP requests.
ActiveRecord is the model portion of MVC (model-view-controller) which is in charge of creating objects whose data is needed to persist within a SQL database. It helps developers create database migrations with methods put in place with a little bit of metaprogramming magic!
We build our data tables and data models out with ActiveRecord, and then control what data we are querying our database for within our Sinatra routes.
Step 1. Have a clear idea of what you want to create and what it'll look like
Try answering questions like “how many models am I going to have? How many views?” This should be clear before you move on and get started
Step 2. Create the necessary models for your project.
Think through your project, in terms of how many relations you’re going to have. You have to understand the type of relationship your tables will have, e.g., one-to-one, one-to-many, or many-to-many.
Step 3. Create a migration to create the Users table with ActiveRecord
Run the following command to create migrations for each model:
bundle exec rake db:create_migration NAME=create_users
The outcome should be timestamped files in the db>migrate folder: (for each model, you’ll perform its migration, one at a time.)
Inside each of the timestamped files, you’ll find an empty change method where you are to list the table attributes (columns) and the datatypes for each column
After filling in the attributes, you’ll get:
Step 3. Run migrations
Migrations will be done using the command:
bundle exec rake db:migrate
Your generated schema should look like this:
Step 4. Seeding data to your DB
In the seeds.rb file, you’ll have to specify how you want to seed your data.
Use the command:
bundle exec rake db:seed
Step 5. Finally, using Sinatra’s built-in routing methods, we can set up a response to fetch request from the front end.
This will return a list of “jsonified” Users by calling the .all and .order methods on a User class, which holds all of the User instances.
On the front end, if you are using a React front end, we can now use the users data we just fetched from the database and set a stateful variable equal to it.
From there, however we decide to display the data is up to us!
Top comments (0)