Rails beginner
Rails beginner

Reputation: 14504

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

Upvotes: 22

Views: 17035

Answers (5)

Chivorn Kouch
Chivorn Kouch

Reputation: 351

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

Upvotes: 0

user3345323
user3345323

Reputation: 21

Very tricky one ... I found a simple solution for this.... This solution works for me

@link = Link.where(:id => params[:id]).first

I am using .first because .where will return an array.Yes, of-course this array has only one element. So, When there is no record with such id, it will return an empty array, assign a blank element to @link ... Now check @link is either blank or not....

Conclusion: No need to provide exception handling for a simple check It is problem with .find it throws exception when no record exist ... Use .where it will return an empty array

And Sorry for my Bad English

Upvotes: 0

Eric Yang
Eric Yang

Reputation: 1889

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

Upvotes: 42

keymone
keymone

Reputation: 8094

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

Upvotes: 8

Wukerplank
Wukerplank

Reputation: 4176

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

Upvotes: 2

Related Questions