[ad_1]
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
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" }
It looks a little different, what’s happening?
-
The get() method takes on two arguments: first -> a String defining the URL route and second -> a Hash containing two keys, :controller and :action.
-
The first Key, :controller, is a Class we define in order to house the Ruby logic for the specified route.
-
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
- 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
What is happening?
-
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.
-
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
- 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>
- 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@.
[ad_2]
Source link