Learning Rails Pt. 2

Sunday, March 19, 2023 | Permalink

Open the http://localhost:3000/about in the web browser. Obviously, you get the No route matches [GET] "/about" error. Because, this route doesn't exist.

The routes for the Rails application are defined in config/routes.rb file. Open this routes.rb file in the text editor. You should see the following code.

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
end

Remove all the comments from this code.

Rails.application.routes.draw do
  
end

Add the /about route line like this.

Rails.application.routes.draw do
  get "/about" => "about#index"
end

This line means, when GET /about is called, run the about's index method. This about is a controller (or class) and index is an action (or method within class).

Reload the /about in the browser. You should now get uninitialized constant AboutController error. Because, we do not have AboutController in about_controller.rb file.

All the controllers for the Rails application are defined within app/controllers folder. In app/controllers, create a file with name about_controller.rb. Open this file in text editor and write the following code.

class AboutController < ApplicationController
end

We defined the AboutController controller that Rails is looking for. This controller is extended with helpful functionalities from ApplicationController controller provided by Rails.

Reload the /about in the browser again. You should now get The action 'index' could not be found for AboutController error. Because, AboutController does not have index action.

Let's define an empty index method in this controller like this.

class AboutController < ApplicationController
  def index
  end
end

Reload the /about in browser for one more time. You should now get No template for interactive request error. Because, we do not have index.html.erb template or view for the method to fulfil the request.

All the views for the Rails application are defined within app/views folder. Create a file with name index.html.erb in folder with name about inside the app/views folder. Here, we need to create about folder first and then index.html.erb file in this created about folder. Open this file in the text editor and write the following code.

<h1>About</h1>

Reload the /about in browser for the last time. You should see the About header in browser now.

In summary, Rails check for the routes in routes.rb file and run the associated action from given controller. Finally, with the help from associated view, request will be fulfilled.

Labels: