Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

ruby on rails - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...