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?
on 2007-01-03 15:19
on 2007-01-03 15:40
hi, try x=Model.find(some_criteria).field || Model.new in case you dont require Model.new can use "" as message for nothing ~gaurav
on 2007-01-03 15:56
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.
on 2007-01-03 16:24
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
on 2007-01-03 16:36
On 1/3/07, Ryan <email@example.com> wrote: > else > Model.new > end > > How are other people handling situations like this? if record = Record.find_by_id 1 record.foo end -- Rick Olson http://weblog.techno-weenie.net http://mephistoblog.com
on 2007-01-03 17:45
gaurav bagga wrote: > "" > > > > > > -- > > Posted via http://www.ruby-forum.com/. > > > > > > > You can also do this... x=Model.find(criteria).field rescue "default value" _Kevin
on 2007-01-04 14:20
Sebastian Delmont has an interesting solution for this situations, he posted it at his blog: http://www.notsostupid.com/blog/2006/06/28/do-or-d... Currently offline, but you can checkit at googles cache: http://22.214.171.124/search?q=cache:4KIQLnwdpLYJ:... 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 http://www.rubycorner.com http://www.hasmanydevelopers.com/