Using a Ruby on Rails backend with a JavaScript frontend

Luoana Chirita
3 min readDec 11, 2018

--

As a Flatiron School student, we learn how to create the backend functionality with Ruby and Ruby on Rails and the front end with JavaScript and React. Before starting to learn React, we have to bring Ruby and JavaScript together (backend and frontend) into one single app.

For other beginners struggling initially to connect the backend to the frontend with Rails and Javascript, I am writing here a basic tutorial.

For our project, we have created 2 separate repositories. We keep everything running locally for now (localhost).

After creating the 2 repositories, we went through all the usual steps for creating the app’s elements:

Backend (Ruby on Rails):

  • Create models and relationships
  • Create the database tables and seed
  • Create controllers with some of the views that might be needed
  • Run Rails s for starting the server (this would open it by default on http://localhost:3000)

Frontend (JavaScript):

  • Create functions that create and append elements
  • Run python -m SimpleHTTPServer for starting the server (this would open it by default on http://localhost:8000)

For the backend, compared to previous projects, one of the main differences now is that we don’t need to create any views. What we previously had in views will now be rendered with JavaScript instead.

The Rails backend is now only meant to create the APIs needed for JavaScript to fetch data from (GET) and to (POST, PATCH, etc.).

Therefore, in order to make this happen, instead of rendering specific views in our controllers, we would render our variables with render json: . For example:

This means that we can now go to http://localhost:3000/hotels in our browser and see the data in json format, which can be now easily fetched with Javascript:

Pretty simple, right?

Now, in order to select which attributes we need in the API, they have to be specified in the model’s serializer:

But what if we have a method in one of our models, how would we access it from the frontend?

The answer is still in the serializer. We define a new method in the serializer class in which we call the method from our model on object. (similar to self. in a regular class). This new method then becomes one of the attributes:

This is just a very basic tutorial to get you started with your first app after learning Ruby and JavaScript. For more info, you should probably look into serializers documentation.

--

--

Luoana Chirita

Full Stack Software Engineer, bootcamp graduate (2018), sharing my learning and my coding journey