简体   繁体   中英

Rails - redirecting to previous page properly

In my application I am trying to enforce that users be signed in to preform certain actions. And when they try to preform these actions when not signed, they are redirected to the 'Sign-In' page, and once they have signed in, they are redirected back to the page they were trying to access. I have all of this working properly with the below code.

Controllers Code

if !(signed_in?)
  session[:return_to] = newcompany_path
  redirect_to signin_path
  flash[:notice] = "You must be signed in to add companies."
else
      @company = Company.new
  @primary_field = @@fields
end

...

redirect_path = session[:return_to]
if user && user.authenticate(params[:session][:password])
    sign_in user
    session[:return_to] = nil
    if (redirect_path == nil)
      redirect_to user
    else
      redirect_to redirect_path
    end
else

The issue I am running into is, if the user clicks away from the sign-in page without actually signing in, the session[return_to] variable is not cleared properly, and if they then go back to sign in later, they are redirected to the wrong page.

So, how would I set it up so if the user clicks away from the sign-in page, the session[:redirect_to] variable is reset?

You could pass the return_to path in query string parameter rather than the session and submit it alongside the sign in form so that it only applies for that form, rather than subsequent requests.

When redirecting to the sign in form, it'd look like:

redirect_to signin_path(return_to: newcompany_path)

Then, in your sign in form, make sure to include a hidden field with the return_to value, like:

hidden_field_tag :return_to, params[:return_to]

Then in your controller action for signing in, you'll check params[:return_to] rather than session[:return_to] to get the path you want.

这是你在找什么?

redirect_to request.referrer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM