first_or_create vs find_or_create_by
first_or_create
似乎记录得少得多,所以我想知道是不是因为这两种方法是同义词。
基本上:
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)
将找到第一个foo
something: value
。 如果不存在,它将使用attributes
来创建它。