DEV Community

Stacy Daniel
Stacy Daniel

Posted on

Js-Quiz `A JavaScript Frontend with a Rails API backend`

This was the moment where I started to feel like an actual developer 😁! For my phrase four project here at Flatiron, We were required to build a single page application using a Rails API backend with a Vanilla JavaScript frontend. I was overjoyed and excited and so I decided to build a Quiz App predominantly on JavaScript.

Note: it's important to have both the frontend and backend in two separate repos, for faster error handling and to also avoid any deployment issues.

Setting Up My Rails API:

To begin creating my Rails Application, I first had to generate a New Rails API.

rails new js-quiz-api --api-database=postgresql

The --api flag ensures that a Rails API only application is created and also assigns the database to use Postgres rather than the default Sqlite3. The Rails Api sets up its dependency gems. I also had to add the active_model_serializers gem to my gemfile, which is used to convert data into a format which can be easily transferred.

class Quiz < ApplicationRecord

   has_many :js_questions
has_many :results
Enter fullscreen mode Exit fullscreen mode




class QuizSerializer < ActiveModel::Serializer


attribute: id, :name, :description, :js_questions
Enter fullscreen mode Exit fullscreen mode




Connecting My Frontend:

My App is structured such that the frontend(JavaScript)sends a get fetch request to my backend(rails api) hosted on http://localhost:3000/quizzesand returns a JSON data to use on my web page.

getQuizzes()

 fetch(this.baseUrl + "/quizzes")
.then(res => res.json())
.then(quizzes => quizzes.forEach(quiz => {
const quizObject = new Quiz(quiz)
quiz.js_questions.forEach(question => {
new Question(question)
})
quizObject.render()
}))
Enter fullscreen mode Exit fullscreen mode




In Conclusion:

Creating this app was a challenge, yet rewarding at the same time. It seemed very simple at first but it did take me some time to figure out all the working parts and to put everything into place. Being a Frontend Developer is a dream of mine and so I am super ecstatic to be on this journey, and to continue to dive deeper into learning JavaScript!
Happy Coding!😀

Top comments (0)