3
6

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のモデル検索の理解を深める

3
Last updated at Posted at 2017-06-08

概要

データベースからのデータを引っ張って来るところで理解が足りていなかったので、色々読み物をしてみる

メモ

  • find

Primarykeyで検索する。

User.find(1)
=> SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1

複数を検索することも可能

User.find([1,2,3]) 
=> SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 2, 3)
  • find_by
    条件に会ったレコードの中から1件だけ取得してくる。
    id指定
User.find_by(id: 1)
=> SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
User.find_by(name: "hoge")
=> SELECT `users`.* FROM `users` WHERE `users`.`name` = 'hoge' LIMIT 1

Record.where(timein: Time.zone.now.all_day)
  • where
    条件にあったレコード全てを取得してくる。
User.where(name: "hoge")
=> SELECT `users`.* FROM `users` WHERE `users`.`name` = 'hoge'

AND検索
whereを並べる感じ。

User.where(name: "hoge").where(id: 1)
=> SELECT `users`.* FROM `users` WHERE `users`.`name` = 'hoge' AND `users`.`id` = 1

OR検索
下記の例をみると、んー。。。って感じなので実際にwhereのOR検索を使いたくなった時にもう少し調べようと思う。

# Rails4

id1 = 1
id2 = 2
User.where("id IN (?) OR id IN (?) " , id1, id2)
=> SELECT `users`.* FROM `users` WHERE (id IN (1) OR id IN (2));

指摘をいただいたので修正。Rails5ではOR検索は下記のように記述する。

# Rails5

User.where(id: 1).or(User.where(id: 2))

参考資料

Railsのモデル検索あれこれ
今から知っておきたいRails 5の新機能・変更点

3
6
2

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
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?