2016-07-29 28 views
1

在活動管理員中,我必須重寫設計密碼控制器以在密碼令牌過期時顯示錯誤。默認情況下,如果令牌過期,它不會顯示任何錯誤。下面是我重寫Rails如何在respond_with後顯示flash消息

# PUT /resource/password 
    def update 
    self.resource = resource_class.reset_password_by_token(resource_params) 
    yield resource if block_given? 

    if resource.errors.empty? 
     resource.unlock_access! if unlockable?(resource) 
     if Devise.sign_in_after_reset_password 
     flash_message = resource.active_for_authentication? ? :updated : :updated_not_active 
     set_flash_message(:notice, flash_message) if is_flashing_format? 
     sign_in(resource_name, resource) 
     else 
     set_flash_message(:notice, :updated_not_active) if is_flashing_format? 
     end 
     respond_with resource, location: after_resetting_password_path_for(resource) 
    else 
     set_minimum_password_length 
     respond_with resource 
    end 
    end 

如果resource.errors.empty?返回false,它不設置任何提示信息的方法。 爲了拋出一個錯誤例外,我做了以下內容:

ActiveAdmin::Devise::PasswordsController.class_eval do 
    def update 
    super 
    if resource.errors.any? 
     flash[:notice] = resource.errors.full_messages.to_sentence 
    end 
    end 
end 

與上面的代碼,錯誤是現在可見的,但不是在同一個頁面加載。但是,它在下一個視圖中顯示。它也工作正常,如果我從設計密碼控制器中複製代碼,並在'respond_with'之前在else塊中添加flash消息,但我不喜歡這種方法。

有沒有辦法在不從設備控制器複製整個方法的情況下顯示flash消息?

+0

你用flash.now試過了嗎? –

+0

flash.now根本不顯示任何錯誤。 – Aitizazk

回答

0

在更新行動的第二線有以下幾點:

yield resource if block_given? 

這意味着,你可以傳遞一個塊這種方法,像這樣:

def update 
    super do |resource| 
    if resource.errors.any? 
     flash[:notice] = resource.errors.full_messages.to_sentence 
    end 
    end 
end 
0

這樣確實也

def create 
@user = User.new(params[:user]) 

respond_to do |format| 
if @user.save 
    flash[:notice] = 'User was successfully created.' 
    format.html { redirect_to(@user) } 
    format.xml { render xml: @user, status: :created, location: @user } 
else 
    format.html { render action: "new" } 
    format.xml { render xml: @user.errors, status: :unprocessable_entity   } 
end 
end 
end 
相關問題