This document provides an overview for creating a simple (non-scaffolded) controller with corresponding views and routes.
While it is possible to create a simple controller without any scaffolding, the examples here make use of a Movie model with the following attributes: title (string), year (integer) and seen (boolean). A scaffold can be created for this model to allow for easy entry of movie records. This document describes the creation of a non-scaffolded controller that presents summary information based on the Movie model.
The follow command creates a controller (called report) and two views (called summary and random):
rails generate controller report summary random
The command does the following:
Each of these items are reviewed in the next sections.
The routes.rb file (in the config folder) provides rules for parsing a URL (e.g. http://localhost:3000/report/summary) and directing the request to the right controller (e.g. report) and action (e.g. summary). For example, the following line indicates that report/summary is a defined path for the report controller and the summary view for a get request:
get "report/summary"
Note that the routes.rb file has a line with resources :movies. This one statement creates all of the routes for the scaffolded code created around the Movie model.
def summary @movie_count = Movie.count @movie_list = Movie.all end
Unless specified otherwise, the view template with the same name is used to display the results. For example, the summary action will then be displayed with the view summary.html.erb.
Views are located in the app/views folder, organized in subfolders that correspond to the controller name that go with them. In addition to HTML code, they consist of dynamic tags that allow for ruby statements (<% ruby-statements %>) and expressions (<%= ruby-expression %>).
Here is an example of view template code that displays all movie titles as a numbered list:
<h1>Movie List</h1> <ol> <% @movie_list.each do |m| %> <li> <%= m.title %> </li> <% end %> </ol>