ruby-on-railsuser-interfacehttp-status-codes

Ruby on Rails - How do I access the HTTP status code in my ERB view?


Suppose I have a controller which sometimes renders the view normally, and sometimes renders the view with HTTP status code 409. How do change what is displayed in the view based on the status code?

I.e. in my controller I'm calling

render my_view status: :conflict

In my_view, I would like to change the data displayed based in the view based on what status code it was called with. I.e.

<%= if <status is normal> "Normal status code" else "Error 409 - Conflict" end %>

Solution

  • In the view, access the ActionDispatch::Response status attribute exposed in the controller, and compare the status code against Rack's enum:

    <%= if controller.response.status == Rack::Utils::SYMBOL_TO_STATUS_CODE[:ok] "Normal status code" else "Not OK status code" end %>