1. Rendering
Rendering 是特别要告诉Controller 中的methods,要哪个view file来显示给用户。We can show Views as we wish!
Earlier each one of our Views rendered based on the method specified in the Controller.
If we write the following method:
def render_demo
end
Rails will always look for the render_demo View. But if we write:
def render_demo
render :home
end
We can tell Rails to render the home View, as long as we have one. Rendering just tells Rails to show the View we specify.
这里这个例子是这样的:1. 在pages_controller.rb文件中,加入一个method: render_demo
class PagesController < ApplicationController def home end def erb_demo end def render_demo render :home #return home page. but return render_demo.html.erb if without this line end end2. 在routes.rb文件中,加入一个route:pages/render_demo
Rails.application.routes.draw do get 'pages/home' root 'pages#home' get 'pages/erb_demo' get 'pages/render_demo' end3. 在render_demo.html.erb文件中:
<%= "This is the render demo template." %>4. 最后在浏览器中请求: localhost:8000/pages/render_demo ,可以得到homepage. 或得到"This is the render demo template"
---------------------
2. redirect
另一个控制view内容的方法是redirect, 它跟rendering有点类似,不过它是重新发送一次request到一个different URL. redirect显示了一个不同的view,Redirecting 产生了一个全新的request.
下面就是我们怎么在rails中使用redirect:
1. 在pages_controller.rb文件中,加入一个method:
def redirect_demo
redirect_to(:action => 'home')
end
2. 在routes.rb 文件中,加入一个route: pages/redirect_demo
3. 在 redirect_demo.html.erb 文件中,代码如下:
<%= "This is your redirect demo template" %>
----------------------
到这里我们就掌握了利用Rails建立一个基本的Static Web App --- 静态web应用
接下来我们要接触动态应用。加油!