There are a few methods: first_or_create_by
, find_or_create_by
, etc which work on the principle:
- talk to the database to try to find the stuff we want
- if we didn't find it, make it ourselves
- save it to the db
Clearly, concurrent calls of these methods could have both threads not find what they want, and at step 3 one will unexpectedly fail.
Seems like a better solution is,
create_or_find
That is:
- create sensible uniqueness constraints in your DB ahead of time.
- save something if you want to save it
- if it worked, good.
- if it didn't work because of a RecordNotUnique exception, it's already there, great, load it
So in what circumstances would I want to use the Rails built-in stuff and not my own (seemingly more reliable) create_or_find
?