47
40

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で条件検索

Posted at

Railsで条件を指定した検索をするには、whereメソッドを使います。

rails_console
Soldier.where(name: 'Eren Yeager')
# => [#<Soldier id: 1, name: "Eren Yeager", age: 15, height: 170, weight: 63, sex: "M">]

whereメソッドには文字列や配列を渡すこともできますが、ハッシュで渡すのが読みやすさ的にも安全性にも良さそうです。比較を条件にするときは文字列で指定しないといけません。(範囲条件はハッシュでできるのに…)

rails_console
Soldier.where("height > 165 and sex = 'F'")
Soldier.where(["height > ? and sex = ?", 165, 'F'])
Soldier.where(["height > :height and sex = :sex", {height: 165, sex: 'F'}])
Soldier.where(height: 165..200, sex: 'F')
# => [#<Soldier id: 2, name: "Mikasa Ackerman", height: 170, sex: "F">, #<Soldier id: 10, name: "Sasha Blouse", height: 168, sex: "F">]

続けて書くこともできます。これは条件が指定されたりされなかったりを実装するときに役立ちそう。

rails_console
Soldier.where(height: 165..200).where(sex: 'F')
# => [#<Soldier id: 2, name: "Mikasa Ackerman", height: 170, sex: "F">, #<Soldier id: 10, name: "Sasha Blouse", height: 168, sex: "F">]

上で述べた比較条件や、その他のハッシュで指定できない条件はArelというライブラリでハッシュ指定できるようになるみたいです。
以下のページに詳しく詳細があります。
ActiveRecord4でこんなSQLクエリどう書くの? Arel編

47
40
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
47
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?