DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on

Route, Controller, Action, View (RCAV)

Routes

Add a route so a user can visit the URL https://my-ruby-rails-app/home

# config/routes.rb

get("/home", { :controller => "pages", :action => "home" })
Enter fullscreen mode Exit fullscreen mode

The first argument to the get() method is a String that contains the address.

The second argument to the get() is a Hash that tells Rails what to do when someone visits the address.

Controller

Controller classes contain the logic of how to respond to requests.

# app/controllers/pages_controller.rb

class PagesController < ApplicationController
  # def action
end        
Enter fullscreen mode Exit fullscreen mode

Files that contain controllers must always end in _controller.rb, and begin with the name of the controller from the route.

Action

# app/controllers/pages_controller.rb

class PagesController < ApplicationController
  def home

    @date = Date.today.day

    render({ :template => "pages_templates/home"})
  end
end        
Enter fullscreen mode Exit fullscreen mode

Action methods are the logic that gets executed by Rails when a user visits an address.

View

render({ :template => "pages_templates/home" })
Enter fullscreen mode Exit fullscreen mode

render() takes a Hash argument. The key of :template is a string that specifies the location of an Embedded Ruby HTML template.

Create a folder within app/views that matches the name that we specified in the render() statement. The file in this folder matches the name in the render() statement. Our file has the home.html.erb extension.

<!-- app/views/pages_templates/home.html.erb -->
<div>
  Today is <%= @date %>
</div>
Enter fullscreen mode Exit fullscreen mode

Rails will embed the variables in the .html.erb template, produce a .html file, and send it back to the user’s browser.

Remember all file, folder, method, variable, and symbol names should be snake_case. Only class names are PascalCase.

Top comments (0)