first_or_create vs find_or_create_by

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)