DEV Community

Lesly Juarez
Lesly Juarez

Posted on

Mod 4

For this project I wanted to build a Single Page Application that would display a trivia game for my significant other. The backend was built with Rails API and the frontend with HTML, CSS, and JavaScript. A user has three categories to select from to start the game. When a user selects a category they get a "Good Luck!" alert and the questions for that category are rendered. Once the user finishes the questions in a category the user can click another category and answer those questions. After a user has finished all of the questions the user has the option to save their score by typing a username.

  1. Back-End Development

I started by working on the back-end of the project by running:

rails new PROJECT_backend --database=postgresql --api

The line above creates a new rails project with PostgreSQL as the database. To deploy the backend of the application to Heroku the database needs to be PostgreSQL since SQLite is not supported.

I created my models by running:
rails g model Category
rails g model Question
rails g model User

A category has_many questions and a question belongs_to a category. The user model did not have any associations since I won't be authenticating a user.

After creating the models, I ran the migrations, added model classes, and associations. I created the seed data and checked the associations using rails console. After verifying that the associations were correct I proceeded to create an api/v1 folder under controllers to namespace the routes.

Rails Console showing associations

I added the gem 'rack-cors' to allow the backend to perform asynchronous requests. I added the gem 'fast_jsonapi' and created the controllers.

rails g controller api/v1/Category
rails g controller api/v1/Question
rails g controller api/v1/User

I namespaced the routes to indicate their association to the first version of an API.

Image description

I verified that the routes were correct by running rails routes and then verifying once again by going to http://localhost:3000/rails/info/routes.

  1. Front-End Development

I began working on the front-end by creating a new repository for and adding an index.html file and a src file that would hold the index.js file. I then added a script tag for the index.js file in the index.html. I created an alert in the index.js file to ensure that the files were connected. I created individual files for questions, categories, and users in the src file and added the end points for each class at the top of the index.js file:
Image description
A POST request can be made if a user decides to save their score after completing the game.

Discussion (0)