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!
exit(false) which terminates execution immediately. exit is an alias for Kernel. exit(true) and raises the SystemExit exception, that may be caught. Also at_exit functions and finalizers are run before termination.
Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
Filters are inherited, so if you set a filter on ApplicationController , it will be run on every controller in your application. The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With