Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a rails controller from executing?

Tags:

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!

like image 461
Yuval Karmi Avatar asked Sep 04 '10 07:09

Yuval Karmi


People also ask

How do you stop an execution in Ruby?

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.

Does redirect to stop execution?

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".

What does a controller do in Rails?

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.

How should you use filters in controllers Rails?

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.


1 Answers

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.

like image 163
Lenny Sirivong Avatar answered Sep 21 '22 07:09

Lenny Sirivong