在Devise用户注册失败后重定向到root_path

时间:2013-05-27 05:34:27

标签: ruby-on-rails-3 ruby-on-rails-3.1 devise

我读过&尝试在多个SO帖子中发布的解决方案(即hereherehere)以及Devise在how to change the path after a failed registration和Devise的RegistrationsController code上的答案无济于事。

而不是像大多数建议的那样在/lib/文件夹中执行自定义失败方法,似乎最容易修复/覆盖它的地方是底部的RegistrationsController#create方法,它是:< / p>

else
  clean_up_passwords resource
  respond_with resource
end

这是(我假设)正确回应user(即将它们重定向到root_path/users),但这里是棘手的部分:我在用户注册时创建了一个嵌套模型,这很困难为此而攻击Devise。我担心如果我弄乱RegistrationsController#create方法,我会打破我完美工作的嵌套模型。

有人还提到Devise解决方案对他们不起作用,但在更改路由问题后让它工作。我怀疑这是我的情况,但这是我的routes.rb文件以防万一:

  devise_for :users, :controllers => { :registrations => "registrations" }
  resources :users

  resources :users do
    resources :lockers
  end

  resources :lockers do
    resources :products
  end

  resources :products
  resources :lockups

  match '/user/:id', :to => 'users#show', :as => :user

  root :to => 'home#index'

我完全感谢任何人都可以提供帮助。我还是Rails的新手,但我总是乐于学习。

编辑:感谢Passionate,我一直在努力弄清楚如何更改注册控制器中最后else块中的逻辑。这是我尝试过的(以及我的noob逻辑):

  # Obviously cleared all the fields since it made no mention of resource
  # redirect_to root_path

  # Too many arguments since root_path takes 0
  # redirect_to root_path resource

  # Just bombed, something about a String somethingorother
  # render root_path

  # Heh, apparently call 'respond_with' and 'redirect_to' multiple times in one action
  # respond_with resource
  # redirect_to root_path

1 个答案:

答案 0 :(得分:0)

首先,您必须修复routes.rb文件。由于您使用的是自定义控制器,因此您还必须自定义devise_scope块。改变

get "signup", :to => "devise/registrations#new"

get "signup", :to => "registrations#new"

并且,如果您尝试覆盖该方法并希望在设计rails注册后设置root_path,您可以这样做

# app/controllers/registrations_controller.rb 
class RegistrationsController < Devise::RegistrationsController
   def create
     build_resource
     // The `build_resource` will build the users . 
    if resource.save
     if resource.active_for_authentication?
      set_flash_message :notice, :signed_up if is_navigational_format?
      sign_up(resource_name, resource)
      respond_with resource, :location => after_sign_up_path_for(resource)
     else
      set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
      expire_session_data_after_sign_in!
      respond_with resource, :location => after_inactive_sign_up_path_for(resource)
     end
    else

     clean_up_passwords resource
     ## replace your logic here
     redirect_to root_path
    end
   end
end

请注意,上述代码适用于devise 2.2.4。目前,由于rails 4和strong_parameter兼容性,github上主分支上的代码有所改变。