LoginSignup
1
1

More than 3 years have passed since last update.

【Rails】find, find_byの違い

Last updated at Posted at 2019-11-06

find, find_byの違い

find

主キー(:id)に一致するオブジェクトを取り出す

find.rb
user = User.find(id: 1)
# => #<Client id: 1, name: "Qiita">

複数の主キーを渡すと,配列で返す

find_array.rb
users = User.find(id: 1, 2)
# => {
# <Client id: 1, name: "Qiita">,
# <Client id: 2, name: "Micheal">
# }

find_by

与えられた条件に一致するオブジェクトを取り出す

find_by.rb
user = User.find_by(name: "Micheal")
# => <Client id: 2, name: "Micheal">
user = User.find_by(id: 1)
# => <Client id: 1, name: "Qiita">

参考リンク

Active Record クエリインターフェイス - Rails ガイド

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