ROR学习系列25-Rails基础8-数据交互之数据绑定

1 创建工程textfields3
2 创建控制器Look,编辑它的代码为
class LookController < ApplicationController
def at
@data_hash = params[:cruncher]  #获得前台标签的所有参数值
@cruncher = Cruncher.new(@data_hash[:crunch]) #把参数值中的:crunch属性提取出来用于做Cruncher构造函数的的参数。
@data = @cruncher.crunch #获得实例中的crunch属性
end
def input
end
end

3 在textfields3\app\models下创建cruncher.rb,代码如下
class Cruncher
attr_reader :crunch
attr_writer :crunch
def initialize(data)
@crunch = data
end
end

4 在textfields3\app\views\look下创建input.rhtml:
<html>
<head>
<title>Using Text Fields</title>
</head>
<body>
<h1>Working With Text Fields</h1>
This Ruby on Rails application lets you read data from text fields.
<br>
<%= start_form_tag ({:action => “at”}, {:method => “post”}) %>
Please enter your name.
<br>
<%= text_field (“cruncher”, “crunch”, {“size” => 30}) %>
<br>
<br>
<input type=”submit”/>
<%= end_form_tag %>
</body>
</html>

注意:这里使用了方法:
<%= text_field (“cruncher”, “crunch”, {“size” => 30}) %>

这个是绑定数据,和前面的标签不一样。
5 在textfields3\app\views\look下创建at.rhtml,代码如下:
<html>
<head>
<title>Using HTML Control Shortcuts</title>
</head>
<body>
<h1>Using HTML Control Shortcuts</h1>
This application uses Rails HTML control shortcuts.
<br>
<br>
Your name is <%= @data %>.
<br>
<br>
</body>
</html>


6 下面我们看一下如何实现在控制器中初始化前台页面。
编辑一下上面的look_controller.rb
class LookController < ApplicationController
def at
@data_hash = params[:cruncher]
@cruncher = Cruncher.new(@data_hash[:crunch])
@data = @cruncher.crunch
end
def input
@cruncher = Cruncher.new(“Steve”)
end
end

你可能感兴趣的:(html,Ruby,Rails)