In the config/routes.rb
file we define routes using the get
method.
get
takes two arguments.
The first is a String
that is the path in the URL that you want to define (”/home”
, for example)
The second argument is a Hash
that needs to have two specific keys, controller
and action
.
{ :controller => "", :action => "" }
The value of the controller
key is the first half of the name of the controller Class that you want to use to process this route. All controller files are located in the app/controllers/
folder.
All Rails apps have a controller called application_controller.rb
so we can do something like:
{ :controller => "application", :action => "" }
The action
key is the name of the method inside the specified controller that will run when the route is reached. You can pick whatever name you like, just make sure to define an instance method by that name in the controller you specified.
All together a valid route will looks something like:
get("/homepage", { :controller => "application", :action => "home" })
A controller is just a class that is used to process the route that is triggered. We can always use application_controller.rb
since it’s in every project, but that can become a very large file if we have a lot of routes.
We often create other controllers that /inherit/ from ApplicationController
and use those controllers to divvy up the logic for our routes. Similar to how all our models inherit from ApplicationRecord
,
class PagesController < ApplicationController
end
Action is just what Rails calls the instance method in the specified controller that is run when the route is visited. When defining the route, we can make up whatever name we want for the action, we just need to make sure that we define a method with that name in the controller.
So if our route is:
get("/homepage", { :controller => "pages", :action => "home" })
We need to define our action like so:
class PagesController < ApplicationController
def home
# ...
end
end
In our controller action, we need to do one of two things:
- Render some response. This could be plain text, JSON, a CSV, or HTML
- Redirect to some other URL (usually some other route that we’ve defined)
The render
method does exactly what is sounds like. The argument is a Hash
.
render({ :template => "folder_name_in_views/file_name.html.erb" })
redirect_to("/home")
#TODO