Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first_or_create vs find_or_create_by

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

like image 529
David Kennell Avatar asked Feb 11 '17 17:02

David Kennell


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

like image 122
ndnenkov Avatar answered Nov 09 '22 17:11

ndnenkov