Rails how to redirect if record is not found

前端 未结 5 1037
时光说笑
时光说笑 2021-02-05 05:42

I am trying to redirect if the record is not found. The page is not redirect and I get the error record not found.

My controller:

def index
@link = Link.         


        
5条回答
  •  长情又很酷
    2021-02-05 06:39

    What I've been doing is putting this at the end of the method:

    rescue ActiveRecord::RecordNotFound
      redirect_to root_url, :flash => { :error => "Record not found." }
    

    Even better, put it as an around_filter for your controller:

    around_filter :catch_not_found
    
    private
    
    def catch_not_found
      yield
    rescue ActiveRecord::RecordNotFound
      redirect_to root_url, :flash => { :error => "Record not found." }
    end
    

提交回复
热议问题