JS and Rails Unite!

Michael Rosenberg
4 min readOct 11, 2020

The first three months, Modules 1–3, of my Flatiron School program revolved around Ruby. Three months of learning and practicing in the world of Ruby each and every day, which as I’m sure many of you will agree with is the absolute best way to learn a new programming language- repetition and consistency being key. So as you could imagine, arriving at Module 4 and having to learn a whole new language, JavaScript, in just a one month period was quite a challenge. I’ll be the first to admit that as I sit here and write this blog, I’ve got a lot of learning and practice ahead of me in order to further develop my JS understanding and skills (Ruby too for that matter, always more to learn!). However, part of why I enjoy the Flatiron curriculum so much is that each module ends with a project, and those projects are EXTREMELY helpful when it comes to strengthening your skills and understanding.

For the Module 4 JavaScript project, we were asked to build a SPA(Single Page Application) including a frontend built with JavaScript, HTML and CSS and a backend API built with Ruby on Rails. This blog is going to illustrate some key steps to getting the project structure set up correctly, as well as some JS basics for correctly integrating the frontend and the backend.

Project Structure- Backend

Once I created a directory for my project, I created two additional directories to house my back and frontend, by entering the following two lines in my terminal:

mkdir backend
mkdir frontend

The next few things I did were create my Rails API in my backend directory, making sure to include the ‘api’ extension since this is just an API application, in order to exclude certain folders and files that aren’t needed for this type of project. Once getting the backend set up, I used scaffolding to set up my two models and their attributes; this sets up your controllers, models, routes with RESTful routing, migrations, etc.:

cd backend/
rails new projectname --api
rails g scaffold posts team:string sport:string moment:text --no-test-frameworkrails g scaffold ratings rating:integer --no-test-framework

After this, I set up my associations in my models files (Post has_many Ratings, Rating belongs_to Post) as well as in my Ratings table migration (t.belongs_to :post). After these steps, I was ready to migrate:

rake db:migrate

The next thing I did was utilize Serializer, a gem that allows you to format your JSON easily on the backend without needing to do any manipulation on the frontend, as well as more easily work with your associations. After adding gem ‘active_model_serializers’ to your Gemfile and running bundle install, enter the following in your terminal (I created a serializer for Posts): rails g serializer post. Then in your serializer file, add the attributes you want to work with along with the desired association (has_many: ratings).

The last couple steps to setting up the backend Rails API is to configure cors in config/initializers/cors.rb, by uncommenting the code already there and then changing origins to an asterisk to include all; then uncomment gem ‘rack-cors’ in your Gemfile and run bundle install.

Frontend

Now that your backend is all set up, it’s time to get your frontend structure set up. You’ll want to go back to the main project directory, then go into your frontend directory and add your JS/HTML/CSS directories and files:

cd ..
cd frontend/
touch index.html
touch index.js
mkdir src
mkdir styles

Inside your src, or source, directory you will add your JS class files which should replicate your backend classes; so in my case, I added post.js and rating.js files to my src directory. And in the styles directory you will add your CSS file for styling (style.css).

Next, inside index.html, you’ll want to get a basic HTML file set up by typing doc and pressing enter, which gives you the template. After this, it’s important to make sure you load your JS files by adding script tags with your JS files inside:

<script src="index.js"></script><script src="src/post.js"></script><script src="src/rating.js"></script>

After following all of these steps, you’re pretty much done with your frontend configuration and are ready to start coding!

JS Basics/Next Steps

Event listener- To make sure that you’ve set up the frontend correctly so far, in your index.js file you can add an event listener for DOM Content Loaded with a debugger to make sure that your JS files are hooked up properly. If you open index.html and refresh the page, you should hit the debugger which lets you know that everything is working so far!

document.addEventListener("DOMContentLoaded", () => {  debugger;})

Setting up JS Classes w/ Constructor functions- In my post.js and rating.js files, I created my classes with constructor functions that accept attributes upon initialization, setting the properties equal to what is being passed in. Here’s an example of my JS Post class:

class Post{  constructor(id, team, sport, moment, ratings){    this.id = id;    this.team = team;    this.sport = sport;    this.moment = moment;    this.ratings = ratings;  }
}

Fetch- For my app, I used fetch requests for Reading, Creating and Deleting Posts as well as Creating Ratings. For each of these, I created a function that makes a fetch request to the endpoint where the information is. The functions take the info from that endpoint and manipulate the DOM depending on the function (list all Posts, create a new Post, etc.). Here’s an example of my fetchPosts function (I used a variable to hold my BASE URL, const BASE_URL = “http://127.0.0.1:3000"):

function fetchPosts(){  fetch(`${BASE_URL}/posts`)  .then(resp => resp.json())  .then(posts => {   for (const post of posts){    let p = new Post(post.id, post.team, post.sport, post.moment,       post.ratings)    p.renderPost();   }  })}

--

--

Michael Rosenberg

Software Engineer/Full Stack Web Developer | Ruby, JavaScript, React, Redux