2017-06-22 26 views
0

在我的Rails 5應用程序中,我使用Devise作爲我的User模型(不使用Confirmable with Devise)。我需要做的是在用User創建一個不同的閃光消息之後替換現有的閃光消息,具體取決於Usercountry_code值。Rails - 如何更改設計歡迎消息,具體取決於屬性值

例如,

# after the user is successfully saved 
if @user.country_code == 'CA' 
    flash[:notice] = "You're in Canada!" 
else 
    flash[:notice] = "You're international!" 
end 

我檢查Devise's documentation,但無法弄清楚如何創建兩個不同版本的成功註冊的消息。

我我能找到的是與新的會話郵件最接近:

Show custom message only on sign_in

Dynamic Flash Messages in Devise

我如何可以改變設計標準的代碼來創建一個可變的歡迎/成功的消息?

回答

0

創建用戶後,Devise會調用after_sign_up_path_for方法來知道重定向到的位置。您可以通過覆蓋此方法更改Flash消息。

class RegistrationsController < Devise::RegistrationsController 
    ... 

    protected 
    def after_sign_up_path_for(resource) 
    # after the user is successfully saved 
    if resource.country_code == 'CA' 
     flash[:notice] = "You're in Canada!" 
    else 
     flash[:notice] = "You're international!" 
    end 

    super 
    end 
end 

希望它有幫助。

0

生成色器件控制器:

rails generate devise:controllers users 

這將產生所有設計中應用程序/控制器/用戶目錄控制器。

添加下面的路線routes.rb中:

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

,然後重寫create動作顯示提示信息,你需要:

相反的set_flash_message!你可以設置flash[:notice] = "You're in Canada!"如你所願。

class Users::RegistrationsController < Devise::RegistrationsController 

... 
... 

# POST /resource 
    def create 
    build_resource(sign_up_params) 

    resource.save 
    yield resource if block_given? 
    if resource.persisted? 
     if resource.active_for_authentication? 
     set_flash_message! :notice, :signed_up # Here you need to set your flash message 
     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}" # Here you need to set your flash message 
     expire_data_after_sign_in! 
     respond_with resource, location: after_inactive_sign_up_path_for(resource) 
     end 
    else 
     clean_up_passwords resource 
     set_minimum_password_length 
     respond_with resource 
    end 
    end 

... 

end