Ruby 2.0.2, Rails 4.0.3, Sorcery 0.8.5
I tried to issue a redirect in my code, only to receive the error message that a redirect or render had already been issued. If that is the case, I'm happy to return. However, if the method is called for any other reason, I'd like to check to see if a redirect or render had been issued and, if not, issue it. The code is authentication based on Sorcery.
In the application controller, I have:
def not_authenticated redirect_to login_url # , :alert => "First log in to view this page." end
This ends up checking for current_user, as follows:
def current_user @current_user ||= @view.current_user unless @view.blank? begin @current_user ||= Associate.find(session[:user_id]) unless session[:user_id].blank? rescue ActiveRecord::RecordNotFound => e return end current_user = @current_user end
In the rescue, I'd like to determine whether or not a redirect or render had already occurred, so that I could redirect_to login_url if not. This would mean, of course, that it was called from a different method, which it is. Thanks.
Render tells Rails which view or asset to show a user, without losing access to any variables defined in the controller action. Redirect is different. The redirect_to method tells your browser to send a request to another URL.
-Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content. -Redirect is used to tell the browser to issue a new request.
In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.
You can call performed?
in your controller to check if render
or redirect_to
has been called already:
performed? # => false redirect_to(login_path) performed? # => true
Read more about performed?
in the Rails docs.
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