view
和 controller
的使用
1, 创建controller,
在工程根目录
下运行如下代码:
ruby script/generate controller meeting
结果: 在app/controllers目录下产生greeting_controller.rb
修改其内容如下:
class GreetingController < ApplicationController
def index
##render :text => "<h1>Welcome to your first Rails application</h1>"
@welcome_message
= "Welcome to your first Rails application" #定义变量
@age
= 8
@table = { #定义数组
'headings'
=> ['first', 'second', 'three'],
'body'
=> [[1,2,3,], [4,5,6], [7,8,9]]
}
end
end
2. 创建视图
ruby script/generate controller meeting index
结果: 在app/views/greeting目录西安产生 index.html.erb
3. 将controller绑定
到view, 修改index.html.erb文件, 调用controller定义的变量
<h1><%= @welcome_message %>
<h1>
<h2>simple expression</h2>
<p>Tom is <%= @age %>
</p>
<h3>Interation using scriptlets
</h3>
<% for i in 1..5 %>
<p>Handing number is <%= i %></p>
<% end %>
<h1>a simple table</h1>
<table>
<tr>
<% @table["headings"].each do |head|%>
<!--定义临时变量hand, 并遍历数组-->
<td>
<b><%= head %><b/>
</td>
<% end %>
</tr>
<% @table["body"].each do |row| %>
<!--定义2级临时变量row,col, 并遍历数组-->
<tr>
<% row.each do |col| %>
<td>
<%= col%>
</td>
<% end %>
</tr>
<% end %>
</table>