Views and Controllers
Computer Science and Engineering College of Engineering The Ohio State University
Recall: Rails Architecture
Copyright By PowCoder代写 加微信 powcoder
Computer Science and Engineering The Ohio State University
Wiring Views and Controllers
Computer Science and Engineering The Ohio State University
A controller is just an ordinary Ruby class Extends ApplicationController
class CourseRosterController <
ApplicationController Location: app/controllers/
Filename: course_roster_controller.rb
Actions are methods in that class def wake_up
A view is an HTML page (kind of) that corresponds to that
Location: app/views/course_roster/
Filename: wake_up.html.erb
Has access to instance variables (e.g., @student) of
corresponding controller!
Recall: Rails Architecture
Computer Science and Engineering The Ohio State University
app/ views/
course_roster/ wake_up.html.erb
app/ controllers/
course_roster_controller.rb
CourseRosterController
Building From Scratch
Computer Science and Engineering The Ohio State University
$ rails new demo
Create CourseRosterController Location: app/controllers
class CourseRosterController <
ApplicationController
Create (empty) method wake_up Add route to config/routes.rb
get 'hi', to: 'course_roster#wake_up'
Create view (wake_up.html.erb) Location: app/views/course_roster
$ rails server
Example: Controller
Computer Science and Engineering The Ohio State University
# in app/controllers/
# filename course_roster_controller.rb
class CourseRosterController <
ApplicationController
def wake_up
# for this simple eg, no code needed
Example: Route Definition
Computer Science and Engineering The Ohio State University
# in config/
# filename routes.rb
Rails.application.routes.draw do
get 'hi', to: 'course_roster#wake_up'
# equivalent to (but shorter than):
# match 'hi', to:
# 'course_roster#wake_up',
# via: [:get]
Example: View
Computer Science and Engineering The Ohio State University
Yo!!
Are you awake?
Single Point of Control
Computer Science and Engineering The Ohio State University
Notice the duplication in names
Controller name (course_roster) used in: Name of the controller class
Filename of controller class implementation Route
Directory name containing views
Action name (wake_up) used in:
Name of the method within controller class
“Solution”: generate all these parts
$ rails g controller course_roster wake_up
Filename of view source
Generating A Controller
Computer Science and Engineering The Ohio State University
$ rails generate controller prof
ask_question visit_office
Results in:
Addition of new routes to config/routes.rb
get ‘prof/ask_question’
Creation of ProfController class app/controllers/prof_controller.rb Definition of methods in ProfController def ask_question … end
def visit_office … end
Creation of 2 views (i.e. one per action) app/views/prof/ask_question.html.erb app/views/prof/visit_office.html.erb
$ rails server
ERb: Embedded Ruby
General templating mechanism
Computer Science and Engineering The Ohio State University
“Template” = a string (usually contents of some file)
Contains (escaped) bits of ruby
<% code %> execute ruby code (“scriplet”)
<%= expr %> replace with result of ruby expr <%# text %> ignore (a comment)
Example: a text file
This is some text.
<% 5.times do %>
Current Time is <%= Time.now %>! <% end %>
Process using erb tool to generate result $ erb example.txt.erb > example.txt
Naming convention: filename.outputlang.erb Example index.html.erb
Many alternatives, eg HAML
Example: books/index.html.erb
Computer Science and Engineering The Ohio State University
Books
<% @books.each do |book| %>
<%= link_to 'New book', new_book_path %>
{ confirm: ‘Are you sure?’ } %>
Computer Science and Engineering The Ohio State University
HTML formed from: Layout + Template
Layout is the common structure of HTML pages
See: app/views/layouts/application.html.erb
<%= yield =>
Action’s template replaces layout’s yield
Layout is where you put site-wide styling
e.g., navigation bar, div’s with CSS classes, footers
Defining and Choosing Layouts
Computer Science and Engineering The Ohio State University
Default layout for responding to action in
ProfController
Or controller can explicitly name layout
class ProfController < ApplicationController
layout "people/snazzy"
# layout "people/snazzy", except: [:show]
There is an application-wide controller that can
also specify a fall-back layout
class ApplicationController <
ActionController::Base
app/views/layouts/prof.html.erb
If not found, then use app/views/layouts/application.html.erb
layout "main"
Demo of Parameters
Computer Science and Engineering The Ohio State University
Add a segment to the route
get 'prof/aq/:msg', # or prof/aq/(:msg) to: 'prof#ask_question'
Pass parameter to action ask_question
Change ask_question to access params
def ask_question
@q = params[:msg]
Use instance variable in view
You said: <%= @q %>!
Computer Science and Engineering The Ohio State University
View/Controller coupling
Layouts and templates
Location of view from name of controller Filename of view from name of action Controller instance variables available
Template for generating HTML Scriplets and expressions
Other templating approaches exist (eg HAML)
Recall: Rails Architecture
Computer Science and Engineering The Ohio State University
app/ views/
course_roster/ wake_up.html.erb
app/ controllers/
course_roster_controller.rb
CourseRosterController
Wiring Views and Controllers
Computer Science and Engineering The Ohio State University
A controller is just an ordinary Ruby class Extends ApplicationController
class CourseRosterController <
ApplicationController Location: app/controllers/
Filename: course_roster_controller.rb
Actions are methods in that class def wake_up
A view is an HTML page (kind of) that corresponds to that action
Location: app/views/course_roster/
Filename: wake_up.html.erb
Has access to instance variables (e.g., @student) of
corresponding controller!
Example: books/index.html.erb
Computer Science and Engineering The Ohio State University
Books
<% @books.each do |book| %>
<%= link_to 'New book', new_book_path %>
{ confirm: ‘Are you sure?’ } %>
Creating a Response
Computer Science and Engineering The Ohio State University
There are 3 ways a controller action can
create the HTTP response:
1. Do nothing: defaults are used 2. Call render method
3. Call redirect method
The first 2 result in HTTP status 200 (OK) Body of response is the HTML of the view
The 3rd results in HTTP status 302 (temporary redirect)
Other responses are possible too (e.g., useful for ajax)
1: Default Response
If the action does not call render (or
redirect), then render is implicitly
called on corresponding view
class BooksController <
ApplicationController
@books = Book.all
Results in call to render
app/views/books/index.html.erb
Computer Science and Engineering The Ohio State University
2: Explicitly Calling Render
Computer Science and Engineering The Ohio State University
Argument: action whose view should be rendered def wake_up
render :show # or render "show" end
def show ...
Action could be from another controller
Action (show) does not get executed
render 'products/show'
Can return text (or json or xml) directly render plain: "OK"
render json: @book # calls to_json render xml: @book # calls to_xml
Note: render does not end action, so don't call it twice ("double render" error)
3: Calling Redirect
Sends response of an HTTP redirect (3xx) Default status: 302 (temporary redirect)
Computer Science and Engineering The Ohio State University
Consequence: client (browser) does another request, this time to the URL indicated by the redirect response
New request is a GET by default
Need URL, can use named route helpers
redirect_to
redirect_to @user # calls redirect_to users_path
redirect_to
Or :back to go back in (client’s)history
Override for permanent redirection (301)
Redirect vs Render
Similarity
render... and return # force termination Difference
Redirect entails 2 round-trips: request, action, response, request, action response Redirect requires a URL as argument, Render requires a view (action)
Common usage for Redirect:
POST-Redirect-GET pattern
Computer Science and Engineering The Ohio State University
Point to a different view
Neither ends the action
GET Blank Form, POST the Form
Computer Science and Engineering The Ohio State University
GET "a blank form"
POST /students
lname: ...etc
GET Blank Form, POST the Form
Computer Science and Engineering The Ohio State University
POST /students
lname: ...etc
GET Blank Form, POST the Form
Computer Science and Engineering The Ohio State University
POST /students
lname: ...etc
GET Blank Form, POST the Form
Computer Science and Engineering The Ohio State University
POST /students
lname: ...etc
POST-Redirect-GET Pattern
Computer Science and Engineering The Ohio State University
Example of POST-Redirect-GET
Computer Science and Engineering The Ohio State University
class BooksController <
ApplicationController
def create
@book = Book.new(book_params)
if @book.save
redirect_to @book, notice: 'Success!'
render :new
Example of POST-Redirect-GET
Computer Science and Engineering The Ohio State University
class BooksController <
ApplicationController
def create
@book = Book.new(book_params)
if @book.save
redirect_to @book, notice: 'Success!'
render :new
A hash returned with redirect response
Set by controller action issuing redirect
flash[:referral_code] = 1234
redirect_to book_url notice: '...'
redirect_to book_url alert: '...'
Flash included in client’s next request Flash available to next action’s view!
<%= flash[:warn] %>…
Computer Science and Engineering The Ohio State University
Common keys can be assigned in redirect
But: flash.now available to first view! flash.now[:notice] = ‘no such book’
Flash: Set, Use, Clear
Computer Science and Engineering The Ohio State University
use flash (then clear)
Using Flash in View
# display just notice message
<%= notice %>
# display all the flash messages
<% if flash.any? %>