LoginSignup
0
0

More than 3 years have passed since last update.

ActiveRecordのwhereの書き方、?の使い方

Posted at

前提

条件絞る時になんとなくwhereで繋いで書いていたので、
見ていて気になった点をまとめて備忘録として書いておきます。

「?」を使う理由

たまにActiveRecordで「?」が使われているのを見ますが、
これは、条件によって使用する数値が変動するときに使います。

User.where("age = ?", params[:age])

上記コードのように、
最初の引数は、文字列で表された条件として受け取り、
その後に続く引数は、文字列内にある疑問符 「 ? 」 に置き換わるようになります。

書き方

これを踏まえて、一通り書き方をまとめます。

一致検索

User.where(name: 'taro', age: 20)
User.where('name = ? and age = ?', 'taro', 20)

〇〇以上、〇〇以下

User.where('age >= ?', 20)
User.where('age <= ?', 20)

LIKE検索

User.where('name like ?', '%ryu%')

LIKE検索を含ませる

User.where('name like ? and age = ?', "%ryu%", 20)
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