DEV Community

Tuyen Ha
Tuyen Ha

Posted on

Sinatra and Active Records to Perform CURD Actions

Sinatra

Sinatra is an open source software web application library and domain-specific language written in Ruby. It does not follow the typical model-view-controller pattern used in other frameworks so therefore Sinatra is considered a microframework rather than a full-stack web development framework such as Ruby on Rails. Simply put, Sinatra is fully dependent on the Rack web server interface and focuses on quickly creating web applications in Ruby with a little less effort. Therefore, making it the perfect small web framework to get you started in web application development with Ruby.

Active Record

Active record is a Ruby gem and a description of an Object Relational Mapping system (ORM). It's basically a Ruby code that runs in between your database and your logic code making changes to your database.

Why Use Active Record?

Now let's talk about why Active Record is used. React is used as a frontend interface in applications but React cannot communicate directly with the database and therefore we need a way to connect our frontend with our backend. This is where Application Programming Interface (API) comes in. Both of the applications uses HTTP and JSON which means we can use this fact to our advantage. Active Record is used to help our React application and our database to understand one another, resulting in a successful collaboration.

Performing CURD with Sinatra

For recap, CURD stands for CREATE, UPDATE, READ, and DELETE. This is the four basic operations that provide users the ability to create data, access the data, update or edit the data and delete the data.

The first step is to create a migration:
$ bundle exec rake db:create_migration NAME=create_games
Running this command will generate a new file in db/migrations and Rake task will also add some starter codes for us.

class CreateGames < ActiveRecord::Migration[6.1]
   def change
   end
end
Enter fullscreen mode Exit fullscreen mode

We're creating a class called CreateGames that inherits from Active Record's ActiveRecord::Migration module. Inside that class, we have a change method which it commonly used for updating the database. The result of this migration is a table with the appropriate columns for games.

class CreateGames < ActiveRecord::Migration[6.1]
   def change
      create_table :games do |t|
        t.string :name
        t.string :genre
        t.integer :price
      end
   end
end
Enter fullscreen mode Exit fullscreen mode

As you can see, games because singular and plural makes a huge difference. Table names are plural because we are creating a games table that we are using with a Game class. In contrary, class names are singular.

Then, we write a block of codes that will create our columns.

We also need the primary key but Active Record will automatically generate that id column for us!

Next, we run our migration:
$ bundle exec rake db:migrate
This command tells Active Records to create a new database file if there isn't one already and update it.

The next step is to create a file game.rb for the Game class and extend the class with ActiveRecord::Base

Class Artist < ActiveRecord::Base
end
Enter fullscreen mode Exit fullscreen mode

Now for the ability to create, update, read, and delete data.

Let's start with the GET Request:

get "/games" do
   games = Game.all
   games.to_json
end
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we first get all the games from the database and return a JSON response with an array of all the game data as shown below.

[
  {
     "id": 1,
     "title": "Pokemon",
     "genre": "Role-playing:,
     "price": 28
  },
  {
     "id": 2,
     "title": "Mario Kart",
     "genre": "Racing",
     "price": 34
  }
]
Enter fullscreen mode Exit fullscreen mode

POST Request

post "/games" do
   games = Game.create(
      title: params[:title],
      genre: params[:genre],
      price: params[:price]
   )
end
Enter fullscreen mode Exit fullscreen mode

Use the HTTP verb /games to handle this request then access the data in the body of the request to create new games. Lastly, send a response to the newly created game as JSON.

param is a special kind of variable in the computer programming language that is used to pass information between functions.

PATCH Request
In my opinion, the PATCH request is the trickiest request of them all because, from the frontend, a PATCH request needs to be utilized in order to handle certain features that allow a user to update their review.

To handle a PATCH request, a PATCH HTTP verb to /games/:id is used in order to find the game that might need updating. We then need to access the data in the body of the request and use that data to update the game in the database. Then again, send a response of the update to JSON.

patch "/games/:id" do
   games = Game.find(params[:id])
   games.update(
      title: params[:title],
      genre: params[:genre],
      price: params[:price]
   )
   games.to_json
end
Enter fullscreen mode Exit fullscreen mode

DELETE Request

delete "/games/:id" do
   games = Game.find(params[:id])
   games.destroy
   games.to_json
end
Enter fullscreen mode Exit fullscreen mode

This one is fairly simple. All we need to do is find the game using the ID, delete that game using games.destroy, and send a response with the deleted game to JSON.

I hope this little tutorial will be proven helpful for those who need a little more clarification!

Top comments (0)