6
first_or_create
似乎遠不如文件記載,所以我想知道是不是因爲這兩種方法是同義詞。first_or_create vs find_or_create_by
first_or_create
似乎遠不如文件記載,所以我想知道是不是因爲這兩種方法是同義詞。first_or_create vs find_or_create_by
基本上是:
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
來創建它。