ryan
1
If find myself doing something like this a lot:
Model.find(some_criteria).field
which throws an exception if nothing is found. I am looking for a
better way of doing something like this:
if Model.find(some_criteria)
Model.find(some_criteria).field
else
Model.new
end
How are other people handling situations like this?
ryan
2
hi,
try
x=Model.find(some_criteria).field || Model.new
in case you dont require Model.new can use “” as message for nothing
~gaurav
ryan
3
gaurav bagga wrote:
hi,
try
x=Model.find(some_criteria).field || Model.new
in case you dont require Model.new can use “” as message for nothing
~gaurav
That doesn’t work for me. I get a ActiveRecord::RecordNotFound error.
ryan
4
hi,
in my previous reply I dint think of the exception hence
so apologies
i tried something
begin
Model.find(criteria)
rescue
“”
end
other thing i tried was
Model.find_by_sql(“select * from models where id = 0”)
gave me empty array if entry was not there
else array with instance of model matching criteria.
hope this helps
regards
gaurav
ryan
5
On 1/3/07, Ryan [email protected] wrote:
else
Model.new
end
How are other people handling situations like this?
if record = Record.find_by_id 1
record.foo
end
–
Rick O.
http://weblog.techno-weenie.net
http://mephistoblog.com
ryan
6
gaurav bagga wrote:
“”
–
Posted via http://www.ruby-forum.com/.
You can also do this…
x=Model.find(criteria).field rescue “default value”
_Kevin
ryan
7
Sebastian D. has an interesting solution for this situations, he
posted it at his blog:
http://www.notsostupid.com/blog/2006/06/28/do-or-do-not-or-maybe-try/
Currently offline, but you can checkit at googles cache:
http://64.233.161.104/search?q=cache:4KIQLnwdpLYJ:www.notsostupid.com/blog/2006/06/28/do-or-do-not-or-maybe-try/+site:www.notsostupid.com+exception&hl=en&ct=clnk&cd=1&client=firefox
Basically what you do is:
module Kernel
Returns ‘value’ in case of an exception, otherwise returns the
execution
of the given block
def try(value = nil)
yield if block_given?
rescue Exception => exception
value
end
end
Hope this simplies your exception handling for this situations
–
Aníbal Rojas