first_or_create的文档似乎要少得多,所以我想知道这是不是因为这两种方法是同义的。
发布于 2017-02-12 01:13:11
基本上:
Foo.where(attributes).first_or_create与以下内容相同:
Foo.find_or_create_by(attributes)#first_or_create有时会被误解,因为人们期望它根据给定的属性进行搜索,但事实并非如此。又名
Foo.first_or_create(attributes)不会搜索满足attributes的foo。它将采用第一个foo (如果存在)。如果查找的条件是用于创建的条件的子集,那么它很有用。又名
Foo.where(something: value).first_or_create(attributes)将找到something: value所在的第一个foo。如果不存在,它将使用attributes创建它。
发布于 2019-06-04 00:14:28
@ndnenkov的答案是正确的,但我想扩展一下为什么我认为可以使用find_or_create
考虑这样一种情况,在创建Foo之前,它必须具有attribute_subset_1或attribute_subset_2。你可以这样(伪地)编码:
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在这种情况下,我认为find_or_create_by不会work...at,至少不容易。我很想知道是否有人对此有不同的看法,但对我来说,我发现first_or_create的这种用法非常适合我的需求。
https://stackoverflow.com/questions/42178674
复制相似问题