Learn Ruby on Rails Book

Moving to an API based architecture

As of now the Rails view is building the list of "Tasks" and the server is responding with HTML.

Now we will switch to API style where the server will primarily send data as 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.

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
6end

If we open new task page by going to the url http://localhost:3000/tasks we will be getting the response in the 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.

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
5end

We have already created our entry point App.jsx, in the chapter for setting up react environment.

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, if it doesn't exist already.

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

Add the following line in to 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
3
4  root "home#index"
5  get '*path', to: 'home#index', via: :all
6end

Now visit http://localhost:3000/ and this time we should get message Home.

Now let's commit these changes:

1git add -A
2git commit -m "Added API based architecture"
⌘K
    to navigateEnterto select Escto close
    Previous
    Next