2017-02-11 88 views

回答

14

基本上是:

Foo.where(attributes).first_or_create 

是一樣的:

Foo.find_or_create_by(attributes) 

#first_or_create有時被誤解爲人們期待它通過賦予的屬性進行搜索,但事實並非如此。阿卡

Foo.first_or_create(attributes) 

不會搜索foo滿足attributes。如果有的話,它將採取第一個foo。如果查找條件是用於創建的條件的子集,那麼這很有用。阿卡

Foo.where(something: value).first_or_create(attributes) 

會發現第一foo其中something: value。如果不存在,它將使用attributes來創建它。