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 1 year has passed since last update.

【WIP】find/ find_by/whereの違い

Last updated at Posted at 2022-08-22

バージョン

  • 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
=> []
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?