バージョン
- Ruby 2.6.6
- Rails 6.0.3
find/ find_by/whereの違い
find
- 検索条件に引っかかる場合
pry(main)> Book.find_by(1)
Book Load (0.2ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = 1 LIMIT 1
=> #<Book id: 1, name: "名前", title: "タイトル", created_at: "2022-01-01 11:11:11", updated_at: "2022-01-01 11:11:11">
pry(main)> Book.find(1).id ## データの中身を取得するとき
=> 1
- 検索条件に引っかからない場合
-
ActiveRecord::RecordNotFound
が発生
-
pry(main)> Book.find(1000)
Book Load (0.3ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = 1000 LIMIT 1
ActiveRecord::RecordNotFound: Couldn't find Book with 'id'=1000
find_by
- 検索条件に引っかかる場合
pry(main)> Book.find_by(id: 1)
Book Load (0.2ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = 1 LIMIT 1
=> #<Book id: 1, name: "名前", title: "タイトル", created_at: "2022-01-01 11:11:11", updated_at: "2022-01-01 11:11:11">
pry(main)> Book.find_by(id: 1) ## データの中身を取得するとき
=> 1
- 検索条件に引っかからない場合
-
nil
を返す
-
pry(main)> Book.find_by(id: 1000)
Book Load (0.2ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = 1 LIMIT 1
=> nil
where
- 検索条件に引っかかる場合
pry(main)> Book.where(id: [1, 2])
Book Load (0.2ms) SELECT `books`.* FROM `books` WHERE `books`.`id` IN (1, 2)
=> [#<Book id: 1, name: "名前1", title: "タイトル1", created_at: "2022-01-01 11:11:11", updated_at: "2022-01-01 11:11:11">,
#<Book id: 2, name: "名前2", title: "タイトル2", created_at: "2022-01-01 11:11:11", updated_at: "2022-01-01 11:11:11">]
pry(main)> Book.where(id: [1, 2])[0].id ## データの中身を取得するとき(戻り値は配列)
=> 1
- 検索条件に引っかからない場合
-
空の配列[]
を返す
-
pry(main)> Book.where(id: 1000)
Book Load (0.2ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = 1000
=> []