first_or_create 与 find_or_create_by [英] first_or_create vs find_or_create_by
问题描述
first_or_create
的文档似乎少得多,所以我想知道这是否仅仅是因为这两种方法是同义词.
first_or_create
seems much less documented, so I wondered if it was just because the two methods are synonymous.
推荐答案
基本上:
Foo.where(attributes).first_or_create
等同于:
Foo.find_or_create_by(attributes)
<小时>
#first_or_create
有时会被误解,因为人们期望它根据给定的属性进行搜索,但事实并非如此.阿卡
#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)
不会搜索满足 attributes
的 foo
.如果有的话,它将使用第一个 foo
.如果查找条件是用于创建的条件的子集,则很有用.阿卡
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)
将找到第一个 foo
其中 something: value
.如果不存在,它将使用 attributes
来创建它.
Will find the first foo
where something: value
. If none is present, it will use attributes
to create it.
这篇关于first_or_create 与 find_or_create_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!