在没有找到id的情况下,整个控制器的总体救援 [英] General rescue throughout controller when id not found - RoR

查看:191
本文介绍了在没有找到id的情况下,整个控制器的总体救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现我的应用程序查找数据库中不存在的id。抛出异常。当然,对于任何Web开发人员而言,这是一个非常标准的情况。

I have stumbled upon a situation where my application looks for an id that does not exist in the database. An exception is thrown. Of course, this is a pretty standard situation for any web developer.

感谢这个答案我知道使用救援交易的情况非常整齐,像这样:

Thanks to this answer I know that using rescue deals with the situation pretty neatly, like so:

def show
  @customer = Customer.find(params[:id])
  rescue ActiveRecord::RecordNotFound #customer with that id cannot be found
    redirect_to action: :index        #redirect to index page takes place instead of crashing
end

如果无法找到客户,用户被重定向到索引页。这是非常好的。

In case the customer cannot be found, the user gets redirected to the index page. This works absolutely fine.

现在,这是很好的,但是我需要在诸如展示,编辑,销毁等操作中进行相同的营救尝试,即每个需要特定ID的控制器方法。

Now, this is all nice, but I need to do the same rescue attempts in actions like show, edit, destroy, etc, i.e. every controller method that needs a specific id.

说了这个,这是我的问题:
Isn'有没有办法一般告诉我的控制器,如果它在任何方法中找不到id,它将重定向到索引页面(或一般来说,执行一个特定的任务)?

Having said that, here's my question: Isn't there any way to generally tell my controller that if it can't find the id in any of its methods, it shall redirect to the index page (or, generally, perform a specific task)?

推荐答案

您必须使用 rescue_from 来完成此任务。请参阅操作控制器概述指南中的示例

You must use rescue_from for this task. See example in the Action Controller Overview Guide

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  private

  def record_not_found
    redirect_to action: :index
  end
end

这篇关于在没有找到id的情况下,整个控制器的总体救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆