且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Devise在表单提交后重写重定向

更新时间:2022-12-07 10:14:32

创建用户表单提交后,创建用户,然后登录,以便您被重定向到的页面实际上是后登录页面。如果您只想在创建用户时更改此页面,您可以在自定义注册控制器中设置 session [#{resource_name} _return_to]

After the create user form is submitted the user is created and then logged in so the page you are being redirected to is actually the after log in page. If you only want to change this page when a user is created you can set session["#{resource_name}_return_to"] in a custom registration controller like this:

class Users::RegistrationsController < Devise::RegistrationsController
  def create
    session["#{resource_name}_return_to"] = some_custom_path
    super
  end
end 

您还可以在routes.rb中为您的用户对象创建根路由,每次登录时都会重定向所有用户:

You can also create a root route for your user object in routes.rb which will redirect all users whenever they log in:

match "user_root" => "users#home"

最后你可以定义 after_sign_in_path_for(resource_or_scope) / code>方法,这将允许您有条件地重定向用户:

Finally you can define the after_sign_in_path_for(resource_or_scope) method in your application_controller and this will allow you to conditionally redirect users:

def after_sign_in_path_for(resource_or_scope)
  if resource_or_scope.is_a?(User)
    some_custom_path    
  else
    super
  end
end