在Rails中返回特定的http状态代码

Sat*_*har 71 ruby-on-rails http http-status-codes http-status-code-503

如何在整个应用程序中返回Rails中的503 Service Unavailable

另外,您如何为特定控制器执行相同操作?

Ser*_*sev 95

您可以使用 head

head 503
# or
head :service_unavailable
Run Code Online (Sandbox Code Playgroud)

  • 我可以使用以下状态符号:service_unavailable所有状态:http://apidock.com/rails/ActionController/Base/render#254-List-of-status-codes-and-their-symbols (11认同)
  • 弃用警告:不推荐使用`:nothing`选项,将在Rails 5.1中删除.使用`head`方法响应空响应体 (3认同)

iwa*_*bed 74

对于整个应用程序:

# ApplicationController
before_filter :return_unavailable_status

private
  def return_unavailable_status
    render :nothing => true, :status => :service_unavailable
  end
Run Code Online (Sandbox Code Playgroud)

如果您想要一个自定义错误页面,您可以:

render 'custom_unavailable_page', :status => :service_unavailable    
Run Code Online (Sandbox Code Playgroud)

如果您不希望它用于特定控制器:

# SomeController
skip_before_filter :return_unavailable_status
Run Code Online (Sandbox Code Playgroud)

  • @Chloe我不相信它的记录很好,但这里有一个列表http://apidock.com/rails/ActionController/Base/render#254-List-of-status-codes-and-their-symbols (3认同)