DEV Community

John Paul Fababaer
John Paul Fababaer

Posted on

Sprint 1: Introduction to Ruby on Rails

After dealing with some Sinatra, it is time to graduate and learn how to utilize Ruby on Rails. It is probably the most intimidating task I've ever had to deal with. Files upon files, and it doesn't seem to end.

Here's the first task, define the routes we want the users to access. To do so, we first have to head to /config/routes.rb. This is where we can define our routes (rails automatically comes with this code):

Rails.application.routes.draw do

end
Enter fullscreen mode Exit fullscreen mode

Inside this do/end block, we can use our get() method (or post(), if necessary) to define our routes. This is where it gets confusing:

get("/divide", { controller: "division:, action: "show_division_form" }
Enter fullscreen mode Exit fullscreen mode

It looks a little different, what's happening?

  1. The get() method takes on two arguments: first -> a String defining the URL route and second -> a Hash containing two keys, :controller and :action.

  2. The first Key, :controller, is a Class we define in order to house the Ruby logic for the specified route.

  3. The second Key, :action, is the method contained within the Class which is the actual Ruby logic we create to perform certain tasks.

Connecting the FIRST dot: config/routes.rb -> app/controllers/[:controller_value]_controller.rb

  1. Create a new file: /app/controllers/[:controller_value]_controller.rb and define the Class specified in routes.rb:
class DivisionController < ApplicationController

   def show_division_form
      render({ template: "division_templates/division_form"})
   end
end
Enter fullscreen mode Exit fullscreen mode

What is happening?

  1. We create a new Class "DivisionController" and inherit from a Parent Class "ApplicationController". In doing so, we can utilize all the useful methods this Child Class would need.

  2. We connect the next dot: inside of render, we use another Hash to tell our route which view template it should connect to. The Value paired with this Key should be the name of the .html.erb file we are going to create to house all of our HTML/CSS.

Connecting the LAST dot: app/controllers/[:controller_value]_controller.rb -> [ChildClass_name]_templates/[template_name].html.erb

  1. To check if we have properly connected the three files (i.e. routes.rb, [controller_name]_controller.rb, and [template_name].html.erb, we have to get back to our roots. In the .html.erb file, write this:
<h1>Hello world!</h1>
Enter fullscreen mode Exit fullscreen mode
  1. When you check the URL: yourdomainname.com/divide, it should now have an H1 heading of "Hello world!"

NICE! Welcome to Ruby on Rails.

CY@.

Top comments (0)