Rails exception catching

Hello I’m writting my first rails application and I would like to catch
when an id cant be found.
For instance have create records 1 2 and 3

I would like to:
records=Record.find(4)
and not get the error page rather somthing like

records=Record.find(4)

if (records==nil)

do stuff

else

do other stuf

end

On 8/11/07, [email protected] Mr [email protected]
wrote:

if (records==nil)

do stuff

else

do other stuf

end

You use rescue and read this chapter about Ruby Exceptions [1].

Good luck!

[1] http://www.rubycentral.com/pickaxe/tut_exceptions.html

Mike De wrote:

Hello I’m writting my first rails application and I would like to catch
when an id cant be found.
For instance have create records 1 2 and 3

I would like to:
records=Record.find(4)
and not get the error page rather somthing like

records=Record.find(4)

if (records==nil)

do stuff

else

do other stuf

end

You probably want something like:

begin
record = Record.find(14)
rescue ActiveRecord::RecordNotFound
puts ‘Record 14 not Found!’
end

Thank you both perfect.

Mike De wrote:

Hello I’m writting my first rails application and I would like to catch
when an id cant be found.
For instance have create records 1 2 and 3

I would like to:
records=Record.find(4)
and not get the error page rather somthing like

records=Record.find(4)

if (records==nil)

do stuff

else

do other stuf

end

Here’s the thing: the reason that AR is throwing an exception when that
fails is because you’re specifically giving it an ID. The assumption is
that you have an ID, you know the record exists, and therefore if it
can’t be found, it’s an exceptional situation.

If the records attached to those IDs are going away for some reason,
either you are stuck using a rescue, or perhaps you can refactor your
problem so that you are making sure whatever dangling objects still have
those ids are cleaned up before you actually try to find them.