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,问题得以解决。查阅资料后发现两者存在显著差异,此前对此缺乏足够重视。
redirect_to用于触发Action方法的跳转,它会向客户端浏览器发送一个新的HTTP请求。常用语法包括:
示例代码如下:
redirect_to :action => 'edit', :id => 7
redirect_to "http://wiisola.javaeye.com/"
redirect_to "/images/1.jpg"
redirect_to :back
其中第4行是回到上一次访问的页面。
render意为“渲染”,它仅在服务器端生成并返回新的模板内容,不会执行对应的Action方法,也不会发起新的请求。其用法如下:
代码示例:
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()
第一行:直接输出纯文本字符串。
第二行:将传入的字符串解析为模板(支持rhtml或rxml格式)进行渲染。
第三行:直接调用指定Action对应的视图模板,功能类似于转发到View层。
第四行:使用指定的模板文件进行渲染,当use_full_path参数设为true时,允许传入相对路径。
第五行:通过模板名称进行渲染,例如:render(:template => "blog/short_list")。
第六行:渲染局部模板(Partial)。
第七行:不输出任何内容,包括Layout布局文件。
第八行:默认行为,相当于render(:action => self),即渲染当前Action对应的视图。
以下是一个手动调用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
尽管解决了表面问题,但深层原因仍需探究:为何render能显示错误信息而redirect_to不能?这可能与Flash消息的生命周期有关,建议后续深入研究源码以彻底厘清机制。