Creating a Simple Backend with ActiveRecord and Sinatra
Published: 2023-06-05 17:47:12

For my Phase 3 (Ruby) project through Flatirons School I needed to use an ActiveRecord backend and a REACT frontend for my app. The Ruby phase was an introduction to backend development and was overall a monster! However, I found working with the backend, creating tables, application controllers, seeding, etc. was a very interesting aspect of this whole process.

I am interested in moving into the **education tech industry** so I intended to create an app that would be a tool for educators or for learners- or both. I decided, because this project required a one to many relationship, that I would build an **_educational resources app_** for learners and educators to search. The landing page looks like this:


![Landing Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jq5sm1rfci47oe28cm1.png)

Users land on this page and can either click the "subjects" link or the button of the same name. It redirects to a list of seeded subject names such as "ART", "SCIENCE", or "THEATRE". These clickable subject names link to individual subject pages that list name, description, resources, urls, etc. 

For my backend I utilized Sinatra/ ActiveRecord. First, I created my migrations: **create_resources** and **create_subjects**. Within these migration files I built out a simple framework table for my database. Here is my create_resources example: 

```
class CreateResources < ActiveRecord::Migration[6.1]
  def change
    create_table :resources do |t|

      t.string :name
      t.string :description
      t.text :url
      t.integer :subject_id
      t.timestamps

    end
  
  end
end
```
The resources table will have columns for name, description, url, subject_id (the foreign key), and timestamps. Subjects will be the "one" and each subject will have "many" resources. I then created the models for each table. This is the resources model, which delineates the belongs_to relationship with the subjects model. The relationship of belongs_to and has_many determines the one-of-many interaction. Here is an example of what the two tables' keys look like and identifies the link between the two with the foreign key of "subject_id": 


![Active Record Tables Drawing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9v2my3ov75upennh2753.jpeg)

Once I finished my create_tables in the migrations I created models for each migration that encapsulate the relationship with inheritance from the ActiveRecord::base and describes the has_many or belongs_to relationship with the other table in my database. Here is an example from my code: 

```
class Subject < ActiveRecord::Base 
has_many :resources, dependent: :destroy 

end
```

Next I worked on the application controller, which holds the keys to the backend/ frontend relationship and how the front end can link into the data in my database. This project is a basic CRUD application so I created some get requests for all "subjects" and singular "subjects" based on the subject_id(id) using GET requests. I did the same for "resources". Additionally I wanted users to be able to create a new resource, so used a POST request and the .create method for this request. 

I also wanted users to be able to use a DELETE request to destroy any resources they didn't not want on the app. If I were to make this app live I would restrict which data could be destroyed by users and which was protected data from my database. 
```
class ApplicationController < Sinatra::Base
  set :default_content_type, 'application/json'


  get '/subjects' do
    subject = Subject.all.to_json(include: :resources)
      end

      get '/subjects/:id' do
    subject = Subject.find(params[:id])
    subject.to_json
    end

      post "/resources" do
   new_resource = Resource.create(
    name: params[:name],
    description: params[:description],
    url: params[:url],
    subject_id: params[:subject_id]
   )
   new_resource.to_json

end

      delete "/resources/:id" do
        deleteResource = Resource.find(params[:id])
        deleteResource.destroy
        # deleteResource.to_json
      end

      patch '/resources/:id' do
        resource = Resource.find_by(params[:id])
        resource.update(
          name: params[:name],
          description: params[:description],
          url: params[:url],
          subject_id: params[:subject_id]
    )
    resource.to_json
      end 
    

      get "/resources" do

        resource = Resource.all
        resource.to_json
    
      end
    
      get "/resources/:id" do
    
        resource = Resource.find(params[:id])
        resource.to_json
    
      end

end
```
I then created a simple seed file using the .create method on  "Subject" and on "Resource" instances. I only put some basic information in here because I felt like functionality was more important than content at this point. Again, if I made this a live app I would seed it with actual, viable information. 

Using the `rake db:migrate` and then `rake db:seed` I finalized my database migration and seeded the tables of the database. I then fired up the server using `rake server` and tested the various requests out on POSTMAN before moving into my frontend using REACT.

I found this whole process to be quite interesting, yet challenging, as I had not built a full-stack app before. It is actually very cool to try and puzzle out what backend relationships, requests, and data is needed to make a frontend meaningful. I found the most difficult part of this project to be the PATCH request, which I am still puzzling out as of now. 

Hope this helped someone along the line who might be struggling with basic ActiveRecord and Sinatra. Thanks