Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Problem with find method
7 Posts
Problem with find method

Calling object.find(1) then it returns object if database contains this type of row with id 1.If the record does not exist with the specified id then it return an error.why? it should returns nil.isn't it??so that i can check like:

if(object.find(1)) do this else do that end Have i made u understood about my issue??Please help me with this issue with example

Person
Forum Rating: 100
Sign In To Rate Post

Strictly speaking, it doesn't return an error, it raises an exception. You can easily rescue that exception for the behaviour you want, like this:

begin
  @model = Model.find(1)
rescue ActiveRecord::RecordNotFound
  # do your else thing
end

Or you can use the inline rescue if that's simpler:

@model = Model.find(1) rescue nil

What you want is

if (Model.find_by_id(1))
  this
else
  that
end

This will return nil if the record does not exist, as you expected. You shouldn't use an exception-throwing method unless you have some use for exceptions.

Or even:


if Model.exists?(1)
  this
else
  that
end

Hi, All(Jason King, Adam Milligan, Sjoerd Andringa)

Thanks for your help. Truly, I am flying to get yours examples....

Person
Forum Rating: 100
Sign In To Rate Post

he can also do:

bc. if @item = Model.find(id) # here you can use @item else # if you didn't find @item end

Elad, no, that will still throw an exception if the @id@ doesn't exist.

7 Posts
Login to add your message