Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails how to redirect if record is not found

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
like image 366
Rails beginner Avatar asked Jul 12 '11 13:07

Rails beginner


3 Answers

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
like image 178
Eric Yang Avatar answered Nov 13 '22 00:11

Eric Yang


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
like image 23
keymone Avatar answered Nov 13 '22 01:11

keymone


You are on the right track, just capture the RecordNotFound exception:

def index
  @link = Link.find(params[:id])
  # should render index.html.erb by default
rescue ActiveRecord::RecordNotFound
  redirect_to(root_url, :notice => 'Record not found')
end
like image 2
Wukerplank Avatar answered Nov 13 '22 02:11

Wukerplank