Learn Ruby on Rails Book

Moving to an API based architecture

Until the section where we displayed the list of Tasks, the server was sending the html. In the sections that follow, we will switch to API style where the server will primarily send data as a json API and the client will build the html.

Deleting Rails views

Now that we are moving to an API based architecture, we will not be needing the Rails view file created in the previous section.

1rm app/views/tasks/index.html.erb

Sending json response from the controllers

Let's open app/controllers/tasks_controller.rb and let's change the index action.

Since tasks in no longer required in its corresponding view file, we can remove the @ sign as it needn't be an instance variable.

1class TasksController < ApplicationController
2  def index
3    tasks = Task.all
4    render status: :ok, json: { tasks: tasks }
5  end

If we open new task page by going to the url http://localhost:3000/tasks we will be getting the response in json format.

Configuring React for API based architecture

Let's create a new controller called Home:

1bundle exec rails generate controller Home

It will generate the following files for us

1Running via Spring preloader in process 8810
2      create  app/controllers/home_controller.rb
3      invoke  erb
4      create    app/views/home
5      invoke  test_unit
6      create    test/controllers/home_controller_test.rb
7      invoke  helper
8      create    app/helpers/home_helper.rb
9      invoke    test_unit
10      invoke  assets
11      invoke    scss
12      create      app/assets/stylesheets/home.scss

Now let's create an index action.

1class HomeController < ApplicationController
2  def index
3    render
4  end

Let's create a file App.jsx

1touch app/javascript/src/App.jsx

App.jsx will act as the single entry point to the react client and react-router will be used for routing in the react side.

We will be serving App.jsx when the home#index action is called. So now, we need to create a view file for home#index.

1touch app/views/home/index.html.erb

Add the following line in app/views/home/index.html.erb

1<%= react_component 'App' %>

Updating Rails routes

Open config/routes.rb and add following lines.

1Rails.application.routes.draw do
2  resources :tasks, only: :index
4  root "home#index"
5  get '*path', to: 'home#index', via: :all

Now let's open app/javascript/src/App.jsx and add the following lines.

1import React from "react";
3const App = () => {
4  return (
5    <h1>This is App.jsx</h1>
6  );
9export default App;

Now visit http://localhost:3000/ and this time we should get message This is App.jsx.

Now let's commit these changes:

1git add -A
2git commit -m "Added API based architecture"