由于最近老是在表單提交后出現沒有反應的現象,發現是在action中的使用render 和 redirect_to的原因,于是就想搞清楚他兩真正的區別在哪里,上一遍的blog也談到了這二者的區別,但是有點淺,
http://www.tkk7.com/fl1429/archive/2009/03/10/258886.html
下面從我們的程序實驗開始:
1,建立controller
test_controller.rb
class TestController < ApplicationController

def test1
puts "test1A"
render :action => "test1"
puts "test1B"
end

def test2
puts "test2A"
redirect_to :action => "test1"
puts "test2B"
end

def test3
puts "test3A"
redirect_to :action => "test3"
puts "test3B"
end

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
瀏覽器中直接輸入地址結果是:
可能是:
1
test1A
2
test1B
3
127.0.0.1 - - [12/Mar/2009:18:10:11 中國標準時間] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
也可能是:
1
127.0.0.1 - - [12/Mar/2009:18:29:50 中國標準時間] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
2
test1A
3
test1B
(2)頁面: test2.rhtml http://localhost:3000/test/test2
結果:
1
test2A
2
test2B
3
127.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
4
test1A
5
test1B
還可以發現最后,瀏覽器的地址的變為: http://localhost:3000/test/test1
(3)頁面test3.rhtml http://localhost:3000/test/test3
1
test3A
2
test3B
3
127.0.0.1 - - [12/Mar/2009:18:12:29 中國標準時間] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3
4
test3A
5
test3B
6
127.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 里,所以頁面三執行的效果是死循環!
posted on 2009-03-12 18:48
fl1429 閱讀(1500)
評論(1) 編輯 收藏 所屬分類:
Rails