Skip to content

Instantly share code, notes, and snippets.

@jelaniwoods
Last active February 11, 2020 00:02
Show Gist options
  • Save jelaniwoods/270ed66c79863cca12817737fd2c29a6 to your computer and use it in GitHub Desktop.
Save jelaniwoods/270ed66c79863cca12817737fd2c29a6 to your computer and use it in GitHub Desktop.

Routing Basics

Connect the RCAV dots

RCAV (Route Controller Action View)

Route

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" })

Controller

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

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

View

In our controller action, we need to do one of two things:

  1. Render some response. This could be plain text, JSON, a CSV, or HTML
  2. Redirect to some other URL (usually some other route that we’ve defined)
Render

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
redirect_to("/home")

#TODO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment