Ruby rails页面跳转知识一点通

Ruby语言可以为我们简便灵活的实现许多功能需求。很多编程人员都开始将目光投向了这项解释型语言。今天我们在这里为大家介绍有关Ruby rails页面跳转的一些实现技巧。#t#

Ruby rails页面跳转代码如下:

  1. if @user.update_attributes
    (
    :password => params
    [:user][:password])   
  2. flash[:notice] = '密码修改完成'   
  3. redirect_to :action => 'index'   
  4. else   
  5. redirect_to :action => 
    'change_pass', 
    :id => @user   
  6. end 

 

后来随手改了下第5行,把redirect_to改为render,居然就OK了。网上找了下才发现redirect_to和render还是有很多区别的,我以前居然一点都没有注意,汗..
redirect_to实现的是action方法的跳转,向浏览器发起一个新的请求,Ruby rails页面跳转具体使用方法如下: 

代码如下:

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

 

其中第4行是回到上一次访问的页面。
render可以翻译成"渲染",也就是说,render仅仅渲染了一个新的模板,而没有执行相应的action。render的用法如下: 

 Ruby rails页面跳转代码如下:

 
 
 
  1. render(:text => string)   
  2. render(:inline => string, 
    [
    :type => "rhtml"|"rxml"])   
  3. render(:action => action_name)   
  4. render(:file => path, 
    [
    :use_full_path => true|false])   
  5. render(:template => name)   
  6. render(:partial => name)   
  7. render(:nothing=>true)   
  8. 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 rails页面跳转 代码如下:

 
 
 
  1. def search   
  2. @results =Search.
    find(params[:query])   
  3. case @results   
  4. when 0 then render 
    :action=> "no_results"   
  5. when 1 then render 
    :action=> "show"   
  6. when 2..10 then render 
    :action=> "show_many"   
  7. end   
  8. end   
  9. def search   
  10. @results =Search.find
    (params[:query])   
  11. case @results   
  12. when 0 then render 
    :action=> "no_results"   
  13. when 1 then render 
    :action=> "show"   
  14. when 2..10 then render 
    :action=> "show_many"   
  15. end   
  16. end  

但是我自己的问题仍然没有解决,为什么用render渲染一个模板能够显示错误信息,但用redirect_to重新请求就没有呢?也许看源码能够解决吧,可惜看不懂,汗..总之以后记住render和redirect_to的用法就是了。

以上就是我们为大家介绍的Ruby rails页面跳转的一些实现方法。

THE END