2.3 RCAV: Controller, Action, View

All of our controller Classes will be in the app/controllers/ folder. There’s already one controller that comes with every Rails app: ApplicationController, found in app/controllers/application_controller.rb. This is the controller that the get("/rock", ...) route is referring to. We will just use this default controller for now. Later we will make separate controllers to keep our code organized.

Here is an example of an action in the controller:

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def play_rock
    self.redirect_to("https://www.wikipedia.org")
  end 
end

We get the Class definition “for free”:

class ApplicationController < ActionController::Base

ApplicationController inherits, with the symbol <, from the ActionController::Base Class, which is inside the Rails gem Since this Class is contained in the gem in our Gemfile, we would need to go to GitHub to actually look at it.. BENP: gem has maybe not been defined or discussed yet. Check. If first time, may need to expand, or leave that to the glossary

Inside of this Class, we define a method:

def play_rock

We could write whatever Ruby steps we want in this method, like getting a random number, calling APIs, etc. But, in the end, the job of an action is to send back a response to the user. A response can be either:

  1. Rendering some data, in any one of many formats:
    • Plain text.
    • HTML for their browser to draw — we’ll learn this soon.
    • JSON for an application to consume — we’ll see JSON when we cover APIs.
    • Less commonly, any other format: CSV, PDF, XML, etc.
  2. Or, the action can redirect the user to another URL.

In fact, we inherited (via < ActionController::Base) a method for each of these: render for the first, and redirect_to for the second.

In our example, we chose to redirect to another URL:

self.redirect_to("https://www.wikipedia.org")

The argument to redirect_to is a String which contains some URL that we want the user to be forwarded to.

This is the V in RCAV. We defined a route to the URL path /rock, and in that route we indicated a controller and an action within that controller. After creating this Class and method, we give the user something to view in their browser.

More often, we will render some HTML for the user, but redirect_to will come in handy in later projects. For example, when we want to send the user directly back to a list of all photos after they’ve deleted a photo.