2013-05-21 35 views
1

考慮下面的控制器方法:如何在正常控制流中引發Rails 3+中的自定義異常?

def create 
    @client = User.find(params[:client][:id]) 
    respond_to do |format| 
     if @client.present? && @client.add_manager(current_user) 
     format.html { redirect_to clients_path, notice: "Successfully added manager" } 
     else 
     format.html { redirect_to clients_path, error: "Could not find client" } 
     end 
    end 
    end 

我如何得到這個在其他塊正確失敗而不是拋出拋出一個RuntimeError它變成了對生產「出事了」?

def add_manager(user) 
    raise "Already a manager" if self.manager_users.include?(user) 
    self.manager_users << user if user.trainer? 
    end 

是代碼...

回答

0

你可以嘗試這樣的事情:

在你的控制器現在

class YourAppName::AlreadyManagerError < StandardError 

end 

改變 「已經是經理」 去你的名字自定義錯誤

def add_manager(user) 
    raise YourAppName::AlreadyManagerError if self.manager_users.include?(user) 
    self.manager_users << user if user.trainer? 
end  

然後在你的ApplicationController中

rescue_from YourAppName::AlreadyManagerError do |exception| 
    render :nothing => "Already a manager", :status => 404 
end 

article更詳細。另外檢查出rescue_from

+0

軌道如何控制流如響應阻塞if和然後#save在該記錄上導致它擊中真正的if塊,然後爲重定向false?我只是想用我自己的方法遵循相同的模式。 –

相關問題