Find_or_create_by_


#1

If I use find_or_create_by_… is it possible to define at was it created
or founded?


#2

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


#3

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


#4

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!:wink:


Phlip