I have a rails application, and in my application controller, I have the following code:
redirect_to :login unless @current_user = User.find_by_uid(session[:cas_user])
@current_user.syncUserRoles
So, this is supposed to redirect them to log in unless it successfully finds their user account. However, it was still going to the next line even if @current_user returned nil.
So, I modified the code to the following:
@current_user = User.find_by_uid(session[:cas_user])
redirect_to :login unless @current_user.present?
@current_user.syncUserRoles
However, it would ignore the inline unless on line 2 and error out with a nilClass error on line 3. I had to finally resort to a full blown if else statement, but I’d like to know what I was doing wrong.
if @current_user.present?
@current_user.syncUserRoles
else
redirect_to :login
end //This works as intended
The confusion here is in how
redirect_toworks, notunless.redirect_tojust sets a302 Movedheader, it won’t return from your action. So the next line will still execute (your@current_user.syncUserRolesline), and when it does render, it will have the 302 status code set.Putting it in a sole
elsebranch, as you’ve discovered, is one way to avoid execution of that line.