Rails how to redirect if record is not found

Viewed 16521

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.find(params[:id])
respond_to do |format|
    if @link.blank?
    format.html { redirect_to(root_url, :notice => 'Record not found') }
    else
    format.html { render :action => "index" }
    end
end
end
5 Answers

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
Related