Trigger a HTTP error in Rails
Asked Answered
D

2

23

I'm trying to call a custom instance of a 403 HTTP error in Rails but I can't seem to figure out how to do this...

I have several user authentication roles and basically if a role tries to browse to an area that it is not authorised to visit I want to display a 403 instead of just redirecting the user.

How do I do this?

Delft answered 7/3, 2010 at 3:22 Comment(1)
I think the accepted answer should be changed -- this one is a better solution, since it's the correct error code as well as a better presentation to the end user: #9130691Decode
R
44

In your controller code add the following line:

render :status => :forbidden, :text => "Forbidden fruit"

Refer to this page for http code to symbol mapping.

Ruby answered 7/3, 2010 at 3:31 Comment(4)
Fantastic! Thanks heaps... FYI you're missing a comma after :forbiddenDelft
Thanks I have updated the answer and added a reference to http code to ruby symbol list.Ruby
The old url to the code mapping is gone. I updated it to point to apidock instead. apidock.com/rails/ActionController/Base/…Psychogenesis
The :text will need to become :plain in newer versions of Rails.Goddamned
A
5

Just for posterity: I think return 403.html is a nicer solution, because it generates a standard page, just like the 404. The above solution only displays the text given. And because someone in good practice can only go to a forbidden page by typing or clicking a link outside the web app, a standard error page is the way to go.

Aestival answered 11/7, 2012 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.