CRUD Routing with Sinatra
Tags: beginners, ruby
Published: 2023-02-11 04:50:36

I am currently finishing up my project for the third phase in my Software Engineer bootcamp. In this phase, I learned how to use Ruby.
 
For this project, students were to design a web app of their choice. Using React for the front-end and Ruby for the back-end. My project is a web application where a user can create a post of their choice. The client can view all the posts or only posts associated with a specific user. The client can also create a profile so they are able to make posts as well.

In a standard Ruby application, you would have migrations, models, and controllers. 
**Migrations** allow you to modify your database in a efficient way. You can create a table, drop the table, add more information to the table and so on. 
**Models** inherit **Active Record::Base** which holds all the methods that allow you to interact with your database.
Now the **Controllers** are the main star of your application. It coordinates the interaction between the user, the views, and the model, along with a number of other things.

So, lets begin creating our application to handle our CRUD actions. 

Let's start with creating a table and migrating it to our database schema. 

```
class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :username
      t.string :password
      t.timestamps
    end
  end
end
```
We will now have a Models folder that will contain a user file with a User class. As you can see below, we have a "has_many" macro inside of our User class. This is a one-to-many association. This tells the User class that each user instance can have many posts. We can now access a list of posts that is associated with a user.

```
class User < ActiveRecord::Base
    has_many :posts
end
```
And lastly, we have a Controllers folder. Inside of that folder, we have a users_controller file with a UsersController class. That class will hold out CRUD actions.

```
class UsersController < ApplicationController
    // methods will go in here    
end
```
Now that we have every thing set up accordingly, we can proceed to coding out our routes. The routes will communicate with the frontend of our application to allow users to **C**reate, **R**ead, **U**pdate, and **D**elete information.
```
class UsersController < ApplicationController
    get '/users' do
   
    end

    post '/users' do
       
    end

    patch '/users/:id' do
     
    end

    delete '/users/:id' do
        
    end
end
```
We now have our layout of our routes. Let's run through what each route will do.

The **get** request is the **Read** portion of our **CRUD** actions. This route will allow the client to see all of our users in the database. 

The **post** request is our **Create** portion of our **CRUD** actions. This route will be used to create a new user and add it to our database. We will first have to get all of the data that the user entered into the form. This will be done in the body of our request. Next, we will use that data to create a new user. And finally, we will send a response of the newly created user as a JSON object to add to our database.

The **patch** request is our **Update** portion of our **CRUD** actions. This route will be used to update an existing user from our database. We would first want to find the user that we are updating by their ID number. We then will use that data to update our selected users' password. And then send that response as a JSON object to our database. 

The **delete** request is obviously our **Delete** portion of our **CRUD** application. This route will be used to delete an existing user from our database. We will find the user that we would like to delete by their ID number, delete the user, and send that response as a JSON. Although in this case, we do not necessarily need to send the response as a JSON object as there would be no data to send because we deleted the user. Instead, we can have an error code that states the user object was deleted.

Now that we know what each request will do for our clients, lets fill in our routes to match their description. 
```
class UsersController < ApplicationController
   
    get '/users' do
        users = User.order(:username)
        users.to_json(include: :posts)
    end

    post '/users' do
        users = User.create(
            first_name: params[:first_name],
            last_name: params[:last_name],
            email: params[:email],
            username: params[:username],
            password: params[:password]
        )
        users.to_json(include: :posts)
    end

    patch '/users/:id' do
        users = User.find(params[:id])
        users.update(
            password: params[:password]
        )
        users.to_json(include: :posts)
    end

    delete '/users/:id' do
        users = User.find(params[:id])
        users.destroy
        users.to_json
        puts "This user has been deleted"
    end
end
```
As you can see in our get, post, and patch requests, the last line of our code is taking that updated information and sending it as a JSON. But in parenthesis next to it, we have **(include: :posts)**. We are sending the users, plus the posts that were created by that user as well. 

We have now successfully created a **CRUD** application and with that knowledge, you can create all the applications your heart desires. 

Happy Coding (: