Yuval Karmi Yuval Karmi - 3 months ago 30
Ruby Question

How to stop a rails controller from executing?

I have the following piece of code

def show
unless logged_in?
login_required
return
end
#some additional code
#that should only execute
#if user is logged in
end


This works perfectly.
Now I'd like to move the login check into a before filter.
The problem is, that when I return from a method outside of show, it doesn't stop the execution of show... how do i stop
show
from going through with the code from an external method (i.e. one that could be called from a before filter)?

Thanks!

Answer

If you return false from a before_filter, then execution of the request will immediately stop.

If you just make your login_required method return false (or redirect) if they aren't logged in, and make it return true if they are, then just before_filter :login_required, it should work perfectly.

Edit: As Lenry states below, this will not work in Rails 2.0.1+ Instead, to stop the request use [code] head :ok in your code