LoginSignup
0
1

More than 1 year has passed since last update.

find, find_by, where メソッドについて

Posted at

find, find_by, whereメソッドについて

こちらの3種のメソッドについて、あまり理解をしないまま使用していたためこちらに自分で調べたことをメモしておく。

findメソッド

主キーに対応するオブジェクトを取り出す

clients = Client.find(10)
# id = 10 の Client を 見つける
clients = Client.find([1, 10])
# id = 1 と 10 の Client を 見つける

find_byメソッド

与えられた条件にマッチするレコードのうち、最初のレコードだけを返す

clients = Client.find_by first_name: 'Lifo'
# => #<Client id: 1, first_name: "Lifo" >
# id: 2 に "Lifo" があっても返ってこない
clients = Client.find_by first_name: 'Jon'
# => nil
# データがないときは nil が返ってくる

find_by!メソッド

clients = Client.find_by first_name: 'Jon'
# => ActiveRecord::RecordNotFound
# nil は返ってこない

whereメソッド

返されるレコードを制限するための条件を指定

  1. 文字列
  2. 配列
  3. ハッシュ
Client.where("orders_count = '2'")
# 文字列
# orders_count が 2 である Client を 探す
Client.where("orders_count = ? ", params[:order])
# 配列
# 条件で使用する数値が変動する場合に使用
Client.where(locked: true)
# ハッシュ
# locked の値が true である Client を 探す

まとめ

find ... 主キーで検索する、配列を使用すれば複数の検索が可
find_by ... レコードからマッチするものを検索する、最初の一つだけが返ってくる
where ... レコードからマッチするものを検索する、マッチしたものが返ってくる

0
1
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
1