Rails 和设计:如何在成功登录后将用户重定向回请求的页面?

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

我正在使用 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

现在如果登录过程成功,如何

  1. 我可以检查它是否是 b)
  2. 如何将用户重新重定向到请求的控制器操作?
  3. 如何通过 AJAX 和 JSON 执行此登录过程?

编辑:我还收到以下错误消息

uninitialized constant ApplicationController::LoginFilter 

当我使用 6.2 Other Ways to Use Filters 中建议的更精细的解决方案而不是上面的解决方案时,我的控制器看起来像这样

# /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

谢谢

冯·斯波茨

您可以在保存请求页面的 application_controller.rb 中添加 before_action 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

然后在成功登录后将用户重定向到此url:

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