Laz*_*Laz 7 ruby ruby-on-rails
如何在Rails中实现动态的自定义错误页面?
例如,使用application.html.erb布局的自定义404错误页面和页面中的一些动态字段.
另外,如何从本地机器测试?
Ton*_*mbe 13
我查看了Google上关于如何执行此操作的一些博客文章,遗憾的是,大多数人似乎依赖于污染您的ApplicationController.
我所做的是使用404消息创建模板,然后使用该模板从rake任务更新public/404.html文件:
# Rake file to generate static 404 page
file "public/404.html" => ["app/views/layouts/application.html.erb"] do |t|
print "Updating 404 page\n"
`curl --silent http://locahost/content/error404 -o public/404.html`
end
Run Code Online (Sandbox Code Playgroud)
现在每当我更新我的全局布局时,404页面都会自动更新.
只需将以下内容添加到ApplicationController:
rescue_from ActiveRecord::RecordNotFound, :with => :render_record_not_found
# Catch record not found for Active Record
def render_record_not_found
render :template => "shared/catchmissingpage", :layout => false, :status => 404
end
# Catches any missing methods and calls the general render_missing_page method
def method_missing(*args)
render_missing_page # calls my common 404 rendering method
end
# General method to render a 404
def render_missing_page
render :template => "shared/catchmissingpage", :layout => false, :status => 404
end
Run Code Online (Sandbox Code Playgroud)
您可以自定义渲染调用(使用模板,使用布局等)并以这种方式捕获错误.现在,它捕获缺少方法和record_not_found你,但也许也有要显示500错误页面,让你可以继续使用这种方法,使之适合你的情况.
对于从本地机器进行测试,它就是这样的.如果您只想让它在生产模式下工作,请添加一个
if ENV['RAILS_ENV'] == 'production'
Run Code Online (Sandbox Code Playgroud)
你很好
检查Henrik Nyh的帖子.其他人也可以通过谷歌找到.
背后的想法:Rails似乎渲染public/404.html404错误.
ActionController::Rescue定义一个rescue_action_in_public调用render_optional_error_file.
| 归档时间: |
|
| 查看次数: |
7899 次 |
| 最近记录: |