Rails how to redirect if record is not found

前端 未结 5 1031
时光说笑
时光说笑 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:41

    I would prefer to use find_by. find_by will find the first record matching the specified conditions. If the record is not found it will return nil, but does not raise exception, so that you can redirect to other page.

    
    def index
      @link = Link.find_by(id: params[:id])
    
      redirect_to(root_url, :notice => 'Record not found') unless @link
    end
    

提交回复
热议问题