Reputation: 4820
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.
Upvotes: 36
Views: 10825
Reputation: 106932
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.
Upvotes: 68