Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Rails to check whether a redirect or render had already been issued?

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.

like image 761
Richard_G Avatar asked Oct 19 '14 01:10

Richard_G


People also ask

What is the difference between render and redirect in Rails?

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.

What is difference between redirect and render?

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

How do I redirect back in Rails?

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.


1 Answers

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.

like image 100
spickermann Avatar answered Oct 06 '22 00:10

spickermann