0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

find_or_initialize_byとは、、?

Posted at

find_or_initialize_byとは

オブジェクトを探してあった場合は取得し、ない場合は新規作成するメソッド。

###find_or_create_byの違いとは?
find_or_create_byは、オブジェクトを探してあった場合は取得することは同じですが、ない場合は新規作成しそれを保存するメソッドです。
保存まで行いたい時はこちらのメソッドを使用します。

##使用例


@user = User.find_or_initialize_by(name: 'test')
  unless @user.persisted?
      # @user が保存されていない場合の処理を書く
      @user.save
    end
end

## 参考
find_or_create_byとfind_or_initialize_byの違い
https://mom0tomo.hateblo.jp/entry/2018/09/14/151910

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?