# Find\_by should return a default

**URL:** <https://www.ruby-forum.com/t/find-by-should-return-a-default/170859>\
**Category:** Rails\
**Created:** [June 23, 2009, 5:47pm UTC](https://www.ruby-forum.com/t/find-by-should-return-a-default/170859 "2009-06-23T17:47:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jc71229](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/bb73d2/32.png) [@jc71229](https://www.ruby-forum.com/u/jc71229)\
**Post date:** [June 23, 2009, 5:47pm UTC](https://www.ruby-forum.com/t/find-by-should-return-a-default/170859/1 "2009-06-23T17:47:48Z")

</div>

Hi,

I am puzzlin for quite a while on this. I use find\_by methods to retieve  
AR objects. In some cases find\_by will return nil if there is no match.  
However I would like to have find\_by return a default object instead.

Is there a way to overload that particular find\_by method? Or whats the  
best way to implement it.

Thanks  
Jens

---

<div class="post-metadata">

**Author:** ![jc71229](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/bb73d2/32.png) [@jc71229](https://www.ruby-forum.com/u/jc71229)\
**Post date:** [June 23, 2009, 5:55pm UTC](https://www.ruby-forum.com/t/find-by-should-return-a-default/170859/2 "2009-06-23T17:55:50Z")

</div>

> I am puzzlin for quite a while on this. I use find\_by methods to  
> retieve  
> AR objects. In some cases find\_by will return nil if there is no  
> match.  
> However I would like to have find\_by return a default object instead.
> 
> Is there a way to overload that particular find\_by method? Or whats  
> the  
> best way to implement it.

My first thought is that overloading this is very dangerous as you  
completely lose the ability to hop into the console and run say  
User.find\_by\_login(‘philip’) and _get_ the ‘philip’ user or nil. I  
could see some nasty side affects here.

If it were me I’d either make it explicit in the code  
“Model.find\_by\_foo() || Model.get\_default()” or extend AR to support  
find\_by\_xxx\_or\_default and then call it that way. Don’t forget though  
that “xxx” might also be “xxx\_and\_yyy\_and\_zzz”.

-philip

---

<div class="post-metadata">

**Author:** ![jc71229](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/bb73d2/32.png) [@jc71229](https://www.ruby-forum.com/u/jc71229)\
**Post date:** [June 23, 2009, 6:48pm UTC](https://www.ruby-forum.com/t/find-by-should-return-a-default/170859/3 "2009-06-23T18:48:39Z")

</div>

Thanks Philip. I used something similar to your suggestion  
“Model.find\_by\_foo() || Model.get\_default()”. I#d rather be explicit on  
that.

Jens

> If it were me I’d either make it explicit in the code  
> “Model.find\_by\_foo() || Model.get\_default()” or extend AR to support  
> find\_by\_xxx\_or\_default and then call it that way. Don’t forget though  
> that “xxx” might also be “xxx\_and\_yyy\_and\_zzz”.
> 
> -philip
