Forum: Ruby on Rails find_or_create_by_...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ead43bcb0202410540a6a7cee5955d46?d=identicon&s=25 Fresh Mix (giga)
on 2009-02-25 20:24
If I use find_or_create_by_.. is it possible to define at was it created
or founded?
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-02-25 20:36
(Received via mailing list)
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
2b2b07fe8688479d2559704d4bf8a264?d=identicon&s=25 Szymon Nowak (szimek)
on 2009-02-25 20:48
(Received via mailing list)
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
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-02-25 21:08
(Received via mailing list)
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
This topic is locked and can not be replied to.