Ruby rails頁面跳轉(zhuǎn)知識(shí)一點(diǎn)通
Ruby語言可以為我們簡(jiǎn)便靈活的實(shí)現(xiàn)許多功能需求。很多編程人員都開始將目光投向了這項(xiàng)解釋型語言。今天我們?cè)谶@里為大家介紹有關(guān)Ruby rails頁面跳轉(zhuǎn)的一些實(shí)現(xiàn)技巧。#t#
Ruby rails頁面跳轉(zhuǎn)代碼如下:
- 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了。網(wǎng)上找了下才發(fā)現(xiàn)redirect_to和render還是有很多區(qū)別的,我以前居然一點(diǎn)都沒有注意,汗..
redirect_to實(shí)現(xiàn)的是action方法的跳轉(zhuǎn),向?yàn)g覽器發(fā)起一個(gè)新的請(qǐng)求,Ruby rails頁面跳轉(zhuǎn)具體使用方法如下:
代碼如下:
- redirect_to :action =>
'edit', :id => 7 - redirect_to "http:
//wiisola.javaeye.com/" - redirect_to "/images/1.jpg"
- redirect_to :back
其中第4行是回到上一次訪問的頁面。
render可以翻譯成"渲染",也就是說,render僅僅渲染了一個(gè)新的模板,而沒有執(zhí)行相應(yīng)的action。render的用法如下:
Ruby rails頁面跳轉(zhuǎn)代碼如下:
- 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行:直接調(diào)用某個(gè)action的模板,相當(dāng)于forward到一個(gè)view
第4行:使用某個(gè)模板文件render, 當(dāng)use_full_path參數(shù)為true時(shí)可以傳入相對(duì)路徑
第5行:使用模板名render,e.x.: render(:template => "blog/short_list")
第6行:以局部模板渲染
第7行:什么也不輸出,包括layout
第8行:默認(rèn)的的render, 相當(dāng)于render(:action => self)
補(bǔ)上一個(gè)手動(dòng)render的例子:
Ruby rails頁面跳轉(zhuǎn) 代碼如下:
- 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
但是我自己的問題仍然沒有解決,為什么用render渲染一個(gè)模板能夠顯示錯(cuò)誤信息,但用redirect_to重新請(qǐng)求就沒有呢?也許看源碼能夠解決吧,可惜看不懂,汗..總之以后記住render和redirect_to的用法就是了。
以上就是我們?yōu)榇蠹医榻B的Ruby rails頁面跳轉(zhuǎn)的一些實(shí)現(xiàn)方法。