1

给定以下控制器方法:

  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

是代码吗...

4

1 回答 1

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

这篇文章更详细。另请查看rescue_from

于 2013-05-21T03:16:40.807 回答