Ruby rails 頁面跳轉(render和redirect_to)

Ruby代碼
複製代碼代碼如下:

if @user.update_attributes(:password => params[:user][:password]) 
flash[:notice] = '密碼修改完成' 
redirect_to :action => 'index' 
else 
redirect_to :action => 'change_pass', :id => @user 
end

後來隨手改了下第5行,把redirect_to改爲render,居然就OK了。網上找了下才發現redirect_to和render還是有很多區別的,我以前居然一點都沒有注意,汗.. 

redirect_to實現的是action方法的跳轉,向瀏覽器發起一個新的請求,具體使用方法如下: 
複製代碼代碼如下:

redirect_to :action => 'edit', :id => 7 
redirect_to "http://wiisola.javaeye.com/" 
redirect_to "/images/1.jpg" 
redirect_to :back 

其中第4行是回到上一次訪問的頁面。 
render可以翻譯成"渲染",也就是說,render僅僅渲染了一個新的模板,而沒有執行相應的action。render的用法如下: 
複製代碼代碼如下:

render(:text => string) 
render(:inline => string, [:type => "rhtml"|"rxml"]) 
render(:action => action_name) 
render(:file => path, [:use_full_path => true|false]) 
render(:template => name) 
render(:partial => name) 
render(:nothing=>true) 
render()

第1行:直接渲染出文本 
第2行:把傳入的string渲染成模板(rhtml或者rxml) 
第3行:直接調用某個action的模板,相當於forward到一個view 
第4行:使用某個模板文件render, 當use_full_path參數爲true時可以傳入相對路徑 
第5行:使用模板名render,e.x.: render(:template => "blog/short_list") 
第6行:以局部模板渲染 
第7行:什麼也不輸出,包括layout 
第8行:默認的的render, 相當於render(:action => self) 
補上一個手動render的例子: 
Ruby代碼 
複製代碼代碼如下:

def search 
@results =Search.find(params[:query]) 
case @results 
when 0 then render :action=> "no_results" 
when 1 then render :action=> "show" 
when 2..10 then render :action=> "show_many" 
end 
end 
def search 
@results =Search.find(params[:query]) 
case @results 
when 0 then render :action=> "no_results" 
when 1 then render :action=> "show" 
when 2..10 then render :action=> "show_many" 
end 
end 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章