简体   繁体   中英

Rails and Devise: How to redirect user back to the requested Page after successful login?

I am using the idiom described in https://guides.rubyonrails.org/v2.3/action_controller_overview.html#other-ways-to-use-filters

# /app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_filter do |controller|
    redirect_to new_login_url unless controller.send(:logged_in?)
  end
end

Now if the signing in process is successful, how

  1. can I examine if it was, and b)
  2. how can I re-redirect the user to the requested controller action?
  3. How do I do this login-process via AJAX and JSON?

EDIT: Also I get the following Error Message

uninitialized constant ApplicationController::LoginFilter 

When I use the more elaborate solution suggested in 6.2 Other Ways to Use Filters instead of the one above such that my Controller looks like this

# /app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :set_return_path, LoginFilter

  def set_return_path
    return if devise_controller?
    session['user_return_to'] = request.url unless current_user
  end

  class LoginFilter

    def self.filter(controller)
      unless controller.send(:logged_in?)
      controller.flash[:error] = "You must be logged in"
      controller.redirect_to controller.new_login_url
    end

   end
  end   
end

Thanks

von Spotz

You can add a before_action in the application_controller.rb where you save the requested page url:

class ApplicationController < ActionController::Base
  before_action :set_return_path

  def set_return_path
    return if devise_controller?

    session['user_return_to'] = request.url unless current_user
  end
end

And then redirect the user to this url after the successful sign-in:

class SessionsController < Devise::SessionsController
 
  def after_sign_in_path_for(resource)
    return root_url if session['user_return_to'].blank?

    session['user_return_to']
  end
end

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