# Find\_or\_create\_by\_

**URL:** <https://www.ruby-forum.com/t/find-or-create-by/161355>\
**Category:** Rails\
**Created:** [February 25, 2009, 8:24pm UTC](https://www.ruby-forum.com/t/find-or-create-by/161355 "2009-02-25T20:24:37Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 25, 2009, 8:24pm UTC](https://www.ruby-forum.com/t/find-or-create-by/161355/1 "2009-02-25T20:24:37Z")

</div>

If I use find\_or\_create\_by\_… is it possible to define at was it created  
or founded?

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 25, 2009, 8:36pm UTC](https://www.ruby-forum.com/t/find-or-create-by/161355/2 "2009-02-25T20:36:19Z")

</div>

Jo Jo wrote:

> If I use find\_or\_create\_by\_… is it possible to define at was it created  
> or founded?

Could you ask the question a different way?

Are you trying to do this (WARNING: made up!)…

find\_or\_create( my\_by\_var, 42 )

…such that you can vary my\_by\_var, and create by different things?

I will now use Google Codesearch to find the missing\_method which wraps  
that  
(that’s a tip in itself!), because I myself am hankering for an  
update\_or\_create\_by…

–  
Phlip

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 25, 2009, 8:48pm UTC](https://www.ruby-forum.com/t/find-or-create-by/161355/3 "2009-02-25T20:48:04Z")

</div>

Hi,

I’m not exactly sure what you’re asking about, but if you want to find  
out if the result was already in the db or was it just created, you  
could use find\_or\_initialize\_by instead:

post = Post.find\_or\_initialize\_by\_title(“something completely  
different”)  
post.new\_record? # false if it was found in the db, true otherwise  
post.save if post.new\_record? # this way you can save it only if it’s  
not already in the db

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 25, 2009, 9:08pm UTC](https://www.ruby-forum.com/t/find-or-create-by/161355/4 "2009-02-25T21:08:14Z")

</div>

szimek wrote:

> post = Post.find\_or\_initialize\_by\_title(“something completely  
> different”)

Way!

Now try this:

post = Post.find\_or\_create\_by\_title(“completely different”) do |post|  
p post.new\_record?  
end

does that print a true?

(Trick question, BTW!😉

–  
Phlip
