Rails how to redirect if record is not found

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

    error is generated by Link.find - it raises exception if object was not found

    you can simplify your code quite a bit:

    def index
      @link = Link.find_by_id(params[:id])
    
      redirect_to(root_url, :notice => 'Record not found') unless @link
    
      respond_to do |format|
        format.html
      end
    end
    

提交回复
热议问题