61
55

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 5 years have passed since last update.

find(42)とfind_by(id: 42)の違いについて

Last updated at Posted at 2015-12-28

#findとfind_by(id:)
大した内容ではないけど知識に穴があったので自分用にメモ。
両方ともRecordをidで検索して結果を返すが、見つからなかった時の挙動が違う。

find

User.find(1000)
  User Load (0.6ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1000 LIMIT 1
=> ActiveRecord::RecordNotFound: Couldn't find User with 'id'=1000

ActiveRecord::RecordNotFound が投げられる。

find_by(id:)

User.find_by(id: 1000)
  User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1000 LIMIT 1
=> nil

nil が返る。

システムの挙動として、Recordが見つからないことが織り込み済みの場合は find_by を使って分岐か何かでnilを処理する。見つからないのが異常なら find を使ってエラーを投げて404ページを表示する。

61
55
1

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
61
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?