Introduction
In order to render a page in Ruby on Rails, there are a couple things that need to be understood.
- Route: A route is the name given to the path of the page.
- Controller: A controller is an class inherited from the Application Controller. This controller allows us to define our actions.
- Actions: Our actions are sort of like functions that we want to run; so far, I've used my actions in order to render my views and manipulate data before render.
- Views: Well what good would our code be if we cannot look at an end result? Not that great, our views allow us to render things to our DOM.
Defining Routes
Inside /root/config/routes.rb we can define our routes as follow:
Rails.application.routes.draw do
get("/route/name", controller: "example_controller", action: "example_action")
end
Defining Controllers, Actions and rendering Views
Inside /root/app/controllers/example_controller.rb, we can declare our our controller and have it inherit from Application Controller. Within our controller we can define our actions as well. Within our actions we can render a view as well.
class PaperController < ApplicationController
def example_action
@greeting = "Congratulations, You Rendered a View in Rails"
render({:template => "untitled/example_view"})
end
end
Defining Views
In /root/app/views/untitled/example_view.html.erb, you can create your view in erb syntax. Yes the extension is .html.erb and I'm not sure why. The untitled directory isn't really part of the structure; however, I added it since one may even separate their views into different directories within their folders.
<h1><%= @greeting %></h1>
Ending
Congratulations! If you followed all the steps above, you successfully rendered a view in Rails. I definitely wrote this article, so I don't forget the RCAV structure in rails and to give my mind a break before I go into Active Record.
Top comments (0)