Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
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
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.
Hi, All(Jason King, Adam Milligan, Sjoerd Andringa)
Thanks for your help. Truly, I am flying to get yours examples....
he can also do:
bc. if @item = Model.find(id) # here you can use @item else # if you didn't find @item end
