Yuval Karmi Yuval Karmi - 1 year ago 104
Ruby Question

How to stop a rails controller from executing?

I have the following piece of code

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

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
from going through with the code from an external method (i.e. one that could be called from a before filter)?


Answer Source

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