简体   繁体   中英

Rails Devise - Pass URL to login

Is there a way for me to pass an URL to the Devise login page, so that when a user logs in, he/she is redirected back to that URL?

Something like:

/login?passthru=/somethingawesome

Or is it better to set a session variable?

Here's what I did

1) In your template set up your sign_in login as follows: Im passing request.fullpath here as an example you can replace this with whatever you want.

<%= link_to "Log in", new_user_session_path(:passthru => request.fullpath %>

2) Next modify ApplicationController as follows: we add a before_filter which sets passthru in the session if it exists. Then we override after_sign_in_path_for to look in the session for passthru. If its not there it will default to root_path. As long as you handle logins with params consistently everywhere this should work. Although it might need some tweaking.

before_filter :store_location

def store_location
  session[:passthru] = params[:passthru] if params[:passthru]
end

def redirect_back_or_default(default)
  session[:passthru] || root_path
end

def after_sign_in_path_for(resource_or_scope)
  redirect_back_or_default(resource_or_scope)
end

Have a method to store the redirect location and a method to access the stored redirect location in application_controller :

def store_location(path)
  session[:return_to] = request.request_uri || path
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
  session[:return_to] = nil
end

Override the after_sign_in_path_for method to redirect the user to the desired location:

def after_sign_in_path_for(resource_or_scope)
  redirect_back_or_default(resource_or_scope)
end

Devise Wiki: How To: Redirect to a specific page on successful sign in out

By the way, the above method is untested and you should test it.

Update for Newer Versions (Ruby 2.2.0, Rails 4.2.0, Devise 3.2.4):

Application_Controller.rb

  before_action :store_location

  private

  def store_location
    session[:requestUri] = params[:requestUri] if params[:requestUri].present?
  end

Devise Sessions_Controller.rb

  # Custom After Sign in Path
  def after_sign_in_path_for(resource_name)
    if session[:requestUri]
      session.delete(:requestUri)
    else
      super
    end
  end

View xxxx.html.erb

<%= link_to ('Get This'), some_require_auth_path(@something.id, requestUri: request.fullpath), class: 'button' %>

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