rubyonrails:Ruby rails 页面跳转(render和redirect_to)

Ruby代码
复制代码 代码如下:

@user.update_attributes(:password => params[:user][:password])
flash[:notice] = '密码修改完成'
redirect_to :action => 'index'

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仅仅渲染了个新模板而没有执行相应actionrender使用方法如下:
复制代码 代码如下:

render(:text => )
render(:inline => , [: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行:把传入渲染成模板(rhtml或者rxml)
第3行:直接某个action模板相当于forward到个view
第4行:使用某个模板文件render, 当use_full_path参数为true时可以传入相对路径
第5行:使用模板名rendere.x.: render(:template => "blog/_list")
第6行:以局部模板渲染
第7行:什么也不输出,包括layout
第8行:默认render, 相当于render(:action => self)
补上个手动render例子:
Ruby代码
复制代码 代码如下:

def search
@results =Search.find(params[:query])
@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])
@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渲染个模板能够显示信息但用redirect_to重新请求就没有呢?也许看源码能够解决吧可惜看不懂汗..总的以后记住render和redirect_to使用方法就是了
Tags:  rubyrails rubyonrails教程 rubyonrails安装 rubyonrails

延伸阅读

最新评论

发表评论