Rails 3设计注册的自定义重定向

时间:2012-03-12 13:26:23

标签: ruby-on-rails devise

我正在使用Devise 1.5.3。

我继承了 Devise::RegistrationsController 来自定义我自己的after_update路径:

class RegistrationsController < Devise::RegistrationsController
   protected
   def after_update_path_for(resource)
     some_path
   end 
end

之后,Rails尝试在 views/registrations/ 中找到注册操作(新增功能,创建功能等)的视图,但 /views/devise/registrations

当然,我可以将所有内容从 /views/devise/registrations 复制到 views/registrations/ 。但它并不适合我,因为我的其他视图(非自定义控制器)仍然在 /views/devise/registrations

我该如何解决?

3 个答案:

答案 0 :(得分:2)

我认为如果你将RegistrationsController的范围扩展到Devise的范围,它应该可行:

class Devise::MyRegistrationsController < Devise::RegistrationsController
  # ...
end

当然,您不能对RegistrationsController使用相同的名称,并且您已将views/devise/registrations文件夹重命名为views/devise/my_registrations,您还必须更新您的routes.rb文件...但是这个设置应该有用......

我认为另一种选择是在初始化程序中覆盖/注入方法:

class Devise::RegistrationsController
  protected
  def after_update_path_for(resource)
    some_path
  end 
end

可能更简单...

答案 1 :(得分:1)

以Vapire的答案为基础。我认为注入选项最简单/最好。

因为我想在导航栏中添加一个永久的“编辑我的注册”,以便可以从任何页面调用它,我还想将用户发送回他们点击的页面。

我发现一种简单的方法是覆盖一些控制器行为并使用会话变量来捕获引用路径。如果必须重新加载表单以更正错误,则使用会话变量可使referrer路径保持不变。

的routes.rb

devise_for :users, :controllers => {:registrations=>'users/registrations'}

控制器/用户/ registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  def edit
    session[:called_from]=request.referer 
    super #revert to standard behaviour
  end

  def after_update_path_for(resource)
    session[:called_from] #returns to the page called from
  end

 end 

答案 2 :(得分:1)

@Vapire接受的答案对我来说对Rails 4不起作用。我不得不像这样覆盖Devise Passwords控制器:

# users/passwords_controller.rb
class Users::PasswordsController < Devise::PasswordsController
 protected
 def after_resetting_password_path_for(resource)
  signed_in_root_path(resource)
 end
end

此处有关于此方法的文档:https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in