What does the first_or_create
/ first_or_create!
method do in Rails?
According to the documentation, the method \"has no description\"
I believe first_or_create
should generally be avoided these days. (Although it's still in Rails 6.1.1.) In 4.0 they added find_or_create_by and friends, which are apparently meant to replace the first_or_create
methods. first_or_create
was once mentioned in the guides, now it's not. And it is no longer documented in the code (since Rails 4.0). It was introduced in Rails 3.2.19.
The reasons are:
It might seem that first_or_create(attrs)
does first(attrs) || create(attrs)
, where in fact it does first || create(attrs)
. The proper usage is:
Model.where(search_attrs).first_or_create(create_attrs)
That is, it might confuse people. first(attrs) || create(attrs)
is what find_or_create_by
does.
Also, using first_or_create
introduces a scope, that might affect the create
callbacks in an unexpected way.
More on it in the changelog (search for first_or_create
).