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

Rails 「findとfind_byの違いについて」

Posted at

はじめに

標題の通り、findとfind_byの違いでつまづいてしまいました。
何とか解決はできましたので、復習も兼ねてoutput致します。
もうすでにご存知の方、省略の仕方等ご存知でしたら、ご教授願います。

一言でいうと・・・

findメソッド : 各モデルのidカラムのデータを指定して、レコードからデータを取得する
find_byメソッド : あるカラムを使って、レコードから最初に一致した1件だけを返してくれる

findメソッドは探してるidがない場合エラーを出してきます。(idを検索キーとしているため)
find_byメソッドなら探しているidがない場合、nilが返ってきます。

findメソッドとは

  • idカラムの値を指定し、その値を持つレコードを取得する。

以下、例ではtasksテーブルのidを指定し、そのidのレコードを取得しています。

find1.png
  • 仮にDBに保存されていないidカラムの値を指定すると、ActiveRecordのエラーが出てしまいます。
find2.png

find_byメソッドとは

あるカラムを使ってレコードを検索し、最初に一致した1件だけ返してくれる。

例)titleカラムが「3/2 Todo」であるレコードを1つ取り出す。

findby1.png

さいごに

日々勉強中ですので、随時更新します。
皆様の復習にご活用頂けますと幸いです。

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?