Search code examples
ruby-on-railscontrol-flow

return from method used by before_filter


I've inherited some rails code that checks to see if a user is defined in a method that is called by a before filter:

before_filter :get_user

def get_user
  @user = User.find(params[:id])
  if !@user
    return false
  end
end

Now, the problem is that this doesn't work :) If the user isn't found, we don't return from the controller, we just return from the get_user() method and then continue execution in show() or update() method with @user set to nil.

My simple solution is to add a redirect to get_user() if @user is nil:

def get_user
  @user = User.find(params[:id])
  if !@user
    redirect_back
    return false
  end
end

Now, my test are passing and everything seems right with the world. But ... I don't understand what's going on. Can someone please explain why the return in get_user() didn't stop execution in the controller completely but only breaks us out of get_user() and causes us to fall into the controller method that was originally called?

Thanks!


Solution

  • http://guides.rubyonrails.org/action_controller_overview.html#filters

    "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. If there are additional filters scheduled to run after that filter, they are also cancelled."

    Pretty self explanatory, but the nature is that you can't return to halt execution in a filter.