Return a specific http status code in Rails

Ruby on-RailsHttpHttp Status-CodesHttp Status-Code-503

Ruby on-Rails Problem Overview


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

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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use head

head 503
# or
head :service_unavailable

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

The following works for me:

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSathish ManoharView Question on Stackoverflow
Solution 1 - Ruby on-RailsSergio TulentsevView Answer on Stackoverflow
Solution 2 - Ruby on-RailsiwasrobbedView Answer on Stackoverflow
Solution 3 - Ruby on-RailsFrank GraciasView Answer on Stackoverflow