Rails - 在登录before_action之后将用户重定向回原始操作

时间:2016-09-06 08:04:41

标签: ruby-on-rails ruby omniauth

我有一个jobs模型和一个创建新工作的链接。我想在访问新的工作表单之前强制用户登录。我已经设置了一个强制登录的before_action。

application_controller.rb

  helper_method :current_user
  helper_method :require_signin!

  def current_user
     @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def require_signin!
    if current_user.nil?
      redirect_to signin_path
    end
  end

jobs_controller.rb

before_action :require_signin!, only: [:new]

的routes.rb

get '/auth/twitter' => 'sessions#new', :as => :signin

sessions_controller.rb

class SessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    user = User.from_omniauth(auth)
    session[:user_id] = user.id
    redirect_to user, :notice => "Signed in!"
  end
end

当前行为 当未登录的用户点击“jobs / new”链接时,事件链为jobs#new - &gt; login - &gt; user(登录后默认重定向)。然后,用户必须导航回jobs#new

期望的行为 当未登录的用户点击“jobs / new”链接时,事件链为jobs#new - &gt; login - &gt; jobs#new

我知道before_action正在拦截原始操作,但我想在登录后完成原始操作。帮助?

1 个答案:

答案 0 :(得分:1)

要实现此功能,您可以在重定向到sign_in路由之前保存会话中的原始路由,例如:

class JobsController
  before_action :save_original_path, only: [:new]
  before_action :require_signin!, only: [:new]

  private

  def save_original_path
    session[:return_to] = new_job_path
  end
end

class SessionsController
  def create
    ...
    redirect_to (session[:return_to] || user), :notice => "Signed in!"
  end
end