由于最近老是在表单提交后出现没有反应的现象,发现是在action中的使用render 和 redirect_to的原因,于是就想搞清楚他两真正的区别在哪里,上一遍的blog也谈到了这二者的区别,但是有点浅,
http://www.blogjava.net/fl1429/archive/2009/03/10/258886.html
下面从我们的程序实验开始:
1,建立controller
test_controller.rb
1 class TestController < ApplicationController 2 3 def test1 4 puts "test1A" 5 render :action => "test1" 6 puts "test1B" 7 end 8 9 def test2 10 puts "test2A" 11 redirect_to :action => "test1" 12 puts "test2B" 13 end 14 15 def test3 16 puts "test3A" 17 redirect_to :action => "test3" 18 puts "test3B" 19 end 20 21 end
2,建立view
在对应的views->test目录下有test1.rhtml,test2.rhtml,test3.rhtml,内容随便写,例如内容都为 hello word
3,启动webrick
到相应的目录下Ruby script/server
4,浏览器中浏览页面
(1)页面test1.rhtml: http://localhost:3000/test/test1
浏览器中直接输入地址结果是:
可能是:
1test1A 2test1B 3 127.0.0.1 - - [12/Mar/2009:18:10:11 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
也可能是:
1127.0.0.1 - - [12/Mar/2009:18:29:50 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1 2test1A 3test1B
(2)页面: test2.rhtml http://localhost:3000/test/test2
结果:
1test2A 2test2B 3127.0.0.1 - - [12/Mar/2009:18:11:10 中国标准时间] "GET /test/test2 HTTP/1.1" 302 98 - -> /test/test2 127.0.0.1 - - [12/Mar/2009:18:11:10 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1 4test1A 5test1B
还可以发现最后,浏览器的地址的变为: http://localhost:3000/test/test1
(3)页面test3.rhtml http://localhost:3000/test/test3
1test3A 2test3B 3127.0.0.1 - - [12/Mar/2009:18:12:29 中国标准时间] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3 4test3A 5test3B 6127.0.0.1 - - [12/Mar/2009:18:12:29 中国标准时间] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3
执行效果是死循环.
由上述实验得到结论:
1,无论是render 还是 redirect_to 都是方法体内的内容全部执行完再跳转,就算跳转了,方法体内的还是会全部执行的
2,render 是跳转到对应的view下rhtml
3,redirect_to 是跳转到对应的 action 里,所以页面三执行的效果是死循环!