42

first_or_create seems much less documented, so I wondered if it was just because the two methods are synonymous.

0

2 Answers 2

69

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.

5
  • 8
    These two are not the same in terms of the SQL they execute, however. first_or_create will use an ORDER BY id LIMIT 1 whereas find_or_create_by will simply use a LIMIT 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).
    – Saul
    Commented Aug 10, 2018 at 1:32
  • 2
    This is indeed the case and means that find_or_*_by ought to be the preferred syntax over where(..).first_or_*
    – Epigene
    Commented Feb 14, 2019 at 12:28
  • 1
    The 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 to first, which orders by id unless some other ordering is specified explicitly.
    – x-yuri
    Commented Feb 1, 2021 at 19:07
  • I might be missing something, but I doubt first_or_create ever suppressed the ORDER BY clause.
    – x-yuri
    Commented Feb 1, 2021 at 19:09
1

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.