Rails:如果没有可用的数据库连接,则显示维护页面 [英] Rails: Display Maintenance Page if No Database Connection Available

查看:90
本文介绍了Rails:如果没有可用的数据库连接,则显示维护页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决方案,当没有可用的Mysql服务器连接时,它将允许我的rails应用程序呈现用户友好的维护页面.

I'm looking for a solution that will allow my rails app to render a user-friendly maintenance page when there is no Mysql server available to connect to.

通常从active_record中的 mysql连接适配器抛出Mysql::Error,例如:

Normally a Mysql::Error is thrown from the mysql connection adapter in active_record Something like:

/!\ FAILSAFE /!\  Wed May 26 11:40:14 -0700 2010
  Status: 500 Internal Server Error
  Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock

是否有一种低开销的方法来捕获此错误并呈现维护页面?

Is there a low-overhead way to catch this error and render a maintenance page instead?

我假设由于连接实际上是在active_record mysql适配器中建立的,因此应用程序在引发错误之前永远不会将其连接到控制器堆栈,因此您无法将其捕获在控制器中.

I'm assuming that since connections are actually made in the active_record mysql adapter the app never makes it to the controller stack before it throws the error, so you can't catch it in a controller.

任何输入将不胜感激.

推荐答案

您可以在root_path控制器所在的任何位置创建视图:

You could create a view in whatever your root_path controller is:

map.root :controller => "foo", :action => "index"

假设您将此视图称为"db_maintenance.html.erb".在您的控制器中,执行以下操作:

Let's say you call this view "db_maintenance.html.erb". In your controller, do this:

def index
  begin
    @widgets = Widget.find(:all)
  rescue Exception => e
    # This will only happen if DB stuff fails
    redirect_to :action => "db_maintenance", :error => e.message
  end
end

...

def db_maintenance
  @error = params[:error] # You might want to do something with this here or in the view
  # renders the app/views/foo/db_maintenance.html.erb view
end

您认为,您可以输入以下内容:

In your view, you could put something like:

<h1>Sorry for the inconvenience</h1>
blah blah blah. This happened because of:
<pre><code><%= @error %></code></pre>

这当然仅在用户点击您网站的主页时有用,但是您可以从那里轻松推断出来.您可以将"def db_maintenance"操作添加到应用程序控制器,并手动指定它也应呈现的视图.这不是完美的,但应该可以完成工作.

This, ofcourse, only helps if the user hits your site's main page, but you could easily extrapolate from there. You could add the "def db_maintenance" action to the application controller and manually specify what view it should render too. It's not perfect, but it should get the job done.

这篇关于Rails:如果没有可用的数据库连接,则显示维护页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆