first_or_create
seems much less documented, so I wondered if it was just because the two methods are synonymous.
2 Answers
Basically:
Foo.where(attributes).first_or_create
Is the same as:
Foo.find_or_create_by(attributes)
#first_or_create
is sometimes misunderstood as people expect it to search by the attributes given, but that is not the case. Aka
Foo.first_or_create(attributes)
Will not search for a foo
that satisfies the attributes
. It will take the first foo
if any are present. It's useful if the conditions for finding are a subset of those used for creation. Aka
Foo.where(something: value).first_or_create(attributes)
Will find the first foo
where something: value
. If none is present, it will use attributes
to create it.
-
8These two are not the same in terms of the SQL they execute, however.
first_or_create
will use anORDER BY id LIMIT 1
whereasfind_or_create_by
will simply use aLIMIT 1
. This doesn't matter in most scenarios, but as your dataset grows you may find this small difference can slow things down by orders of magnitude (even with indexes in place).– SaulCommented Aug 10, 2018 at 1:32 -
2This is indeed the case and means that
find_or_*_by
ought to be the preferred syntax overwhere(..).first_or_*
– EpigeneCommented Feb 14, 2019 at 12:28 -
1The commit nodoc the first_or_create methods and document alternatives explains why it is less documented.– 谷口昂平Commented May 13, 2020 at 9:31
-
Yep, there's more to it then just possible confusion. More on it in my answer. @Saul
first_or_create
appeared in Rails 3.2.19 and was sort of deprecated in Rails 4.0. During that time its code didn't change much. It all comes down tofirst
, which orders byid
unless some other ordering is specified explicitly.– x-yuriCommented Feb 1, 2021 at 19:07 -
I might be missing something, but I doubt
first_or_create
ever suppressed theORDER BY
clause.– x-yuriCommented Feb 1, 2021 at 19:09
@ndnenkov's answer is right on but I wanted to expand on why I think one might use find_or_create
:
Consider the case when Foo must have either attribute_subset_1
or attribute_subset_2
before it can be created. One could (pseudo)code this as:
if attribute_subset_1 then
Foo.where(attribute_subset_1).first_or_create(attributes)
elsif attribute_subset_2 then
Foo.where(attribute_subset_2).first_or_create(attributes)
else
Raise error " insufficient attributes"
end
This is a case where I think find_or_create_by
does not work...at least not easily. I would be curious to hear if anything sees this differently but for me I found this use of first_or_create
perfect for my needs.