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!
In rails versions 2.0.1 and above, you need to redirect or send a response to halt execution of the action.
From Agile Web Development with Rails Errata:
#45840: The following is incorrect:
"If a before filter returns false, processing of the filter chain terminates, and the action is not run. A filter may also render output or redirect requests, in which case the original action never gets invoked."
A before_filter does not stop processing the filter chain on on return false any longer.
From release notes of Rails 2.0.1: * Changed before_filter halting to happen automatically on render or redirect but no longer on simply returning false [David Heinemeier Hansson]
--Rob Christie
redirect_to
, render
, and head
will all halt execution. For example, head :ok
will respond to the request with only the OK HTTP response code, and the action will not execute.
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 head :ok
in your code
To halt callback chain in Rails 5 you can use
throw :abort
精彩评论