Ruby-on-rails 在 Rails 中返回特定的 http 状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8890351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:39:38  来源:igfitidea点击:

Return a specific http status code in Rails

ruby-on-railshttphttp-status-codeshttp-status-code-503

提问by Sathish Manohar

How do you return 503 Service Unavailablein Rails for the entire application?

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

Also, how do you do the same for specific controllers?

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

回答by Sergio Tulentsev

You can use head

您可以使用 head

head 503
# or
head :service_unavailable

回答by iwasrobbed

For the entire application:

对于整个应用程序:

# ApplicationController
before_filter :return_unavailable_status

private
  def return_unavailable_status
    render :nothing => true, :status => :service_unavailable
  end

If you wanted a custom error page, you could do:

如果你想要一个自定义错误页面,你可以这样做:

render 'custom_unavailable_page', :status => :service_unavailable    

If you don't want it for specific controllers:

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

# SomeController
skip_before_filter :return_unavailable_status

回答by Frank Gracias

The following works for me:

以下对我有用:

format.any { render :json => {:response => 'Unable to authenticate' },:status => 401  }

The :responsefor the HTML response just in case it's accessed from the browser.

:response对HTML响应以防万一它是从浏览器访问。

The render head 503 does not seem to be working with the above statement.

渲染头 503 似乎不适用于上述语句。