2015-06-26 35 views
0

我有一個Rails應用程序,它使用Devise進行用戶註冊/驗證。註冊表單和登錄表單都是我的域名的根源。註冊失敗時,如何將用戶重定向到特定頁面?

當用戶註冊失敗時(例如因爲他們輸入了已經佔用的電子郵件地址),默認情況下,Devise重定向到/users

我該如何改變這種情況?我希望用戶被定向到/

我有一個失敗的登錄嘗試成功實施了這一點,用下面的代碼:

class CustomFailure < Devise::FailureApp 
    def redirect_url 
    "/" 
    end 

    def respond 
    if http_auth? 
     http_auth 
    else 
     redirect 
    end 
    end 
end 

和:

config.warden do |manager| 
    manager.failure_app = CustomFailure 
end 

至於詳細on the project's homepage

有什麼方法可以擴展/改變這個,以便失敗的註冊也可以重定向到我的域的根目錄?

我使用Ruby 2.2.0,Rails 4.2.0和Devise 3.4.1。

回答

1

您可能需要子類Devise::RegistrationsController並覆蓋創建操作。只需從here複製創建方法,並修改保存失敗時的重定向。

# app/controllers/registrations_controller.rb 
class RegistrationsController < Devise::RegistrationsController 


    def create 
    build_resource 
    if resource.save  
     set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource) 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) 
     respond_with_navigational(resource) { render_with_scope :new } 
    end 
    end 


    end 

# The path used after sign up for inactive accounts. You need to overwrite 
# this method in your own RegistrationsController. 
def after_inactive_sign_up_path_for(resource) 
    new_user_session_path 
end 

更改路線,告訴設計使用您的控制器:

# config/routes.rb 
devise_for :users, :controllers => {:registrations => "registrations"} 
+0

感謝您的幫助。這樣可行。但是,如果我'redirect_to root_url',那麼我將失去表單將顯示的任何錯誤消息。任何想法如何解決這個問題?登記表正在主頁上部分顯示。 –

+0

如何向重定向添加錯誤?我的意思是'redirect_to root_url,錯誤:'註冊失敗'.'那是你想要添加的嗎?或者你的意思是錯誤,如「電子郵件是不正確的」? – ZuzannaSt

+0

嗨更新我的答案通過添加創建操作... @JackZelig ...使用它,讓我知道 – Milind

1

我相信你可以看看this問題。當用戶沒有保存時​​,您可以重寫Devise RegistrationsController並將redirect_to方法添加到else

例如:

# app/controllers/registrations_controller.rb 
class RegistrationsController < Devise::RegistrationsController 
    def new 
    super 
    end 

    def create 
    if @user.save? 
     #something 
    else 
     redirect_to your_path, error: 'Registration failed' 
    end 
+0

謝謝你的幫助。它的工作原理,但我看到失去了錯誤信息(見上文)。任何想法我做錯了什麼? –

相關問題