给出以下控制器方法:
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
如何在else块中正确地使其失败,而不是在生产中抛出一个“运行错误”的RuntimeError?
def add_manager(user)
raise "Already a manager" if self.manager_users.include?(user)
self.manager_users << user if user.trainer?
end
是代码......
答案 0 :(得分: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