first_or_create vs find_or_create_by

Dav*_*ell 20 activerecord ruby-on-rails

first_or_create 似乎没那么记录,所以我想知道是不是因为这两种方法是同义词.

ndn*_*kov 38

基本上:

Foo.where(attributes).first_or_create
Run Code Online (Sandbox Code Playgroud)

是相同的:

Foo.find_or_create_by(attributes)
Run Code Online (Sandbox Code Playgroud)

#first_or_create有时人们会误解人们希望它按照给定的属性进行搜索,但事实并非如此.阿卡

Foo.first_or_create(attributes)
Run Code Online (Sandbox Code Playgroud)

不会搜索foo满足的attributes.foo如果存在,它将采用第一个.如果查找条件是用于创建的条件的子集,则它很有用.阿卡

Foo.where(something: value).first_or_create(attributes)
Run Code Online (Sandbox Code Playgroud)

会找到第一个foo在哪里something: value.如果不存在,则将用于attributes创建它.

  • 但是,就它们执行的SQL而言,这两者并不相同.`first_or_create`将使用`ORDER BY id LIMIT 1`而``find_or_create_by`将只使用`LIMIT 1`.这在大多数情况下都无关紧要,但随着数据集的增长,您可能会发现这种微小差异可能会使事情减少数量级(即使索引已到位). (4认同)
  • 确实如此,这意味着 `find_or_*_by` 应该是 `where(..).first_or_*` 的首选语法 (2认同)