First_or_create vs find_or_create_by

first_or_create seems a lot less documented, so I wondered if this was just because the two methods are synonymous.

+18
source share
2 answers

Basically:

 Foo.where(attributes).first_or_create 

Same as:

 Foo.find_or_create_by(attributes) 

#first_or_create sometimes misunderstood because people expect it to be searched for by the given attributes, but this is not so. Aka

 Foo.first_or_create(attributes) 

Will not look for foo attributes . He will accept the first foo , if any. This is useful if the search terms are a subset of those used to create. Aka

 Foo.where(something: value).first_or_create(attributes) 

Find the first foo , where something: value . If none is present, it will use attributes to create it.

+33
source

@Ndnenkov's answer is correct, but I would like to find_or_create on why I think that find_or_create can be used:

Consider the case where Foo must have attribute_subset_1 or attribute_subset_2 before it can be created. You can (pseudo) encode 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 the case when I think find_or_create_by not working ... at least not easily. I would be curious to hear if something sees it differently, but I found that using first_or_create perfect for my needs.

0
source

Source: https://habr.com/ru/post/1014902/


All Articles