LoginSignup
6
6

More than 5 years have passed since last update.

Rails4 | 新規・変更機能 | where.notによる否定クエリ

Posted at

Rails4 | 新規・変更機能 | where.notによる否定クエリ

概要

Rails3以前では否定のクエリを記述する際に下記のようにする必要がありました。

if age.nil?
  Person.where('age IS NOT NULL')
else
  Person.where('age <> ?', age)
end

Rails4では where.not が追加され、下記のようにシンプルに記述できるようになっています。

Person.where.not(age: age)

サンプル

仕様

  • 下記で scaffold した状態をベースとする
rails g scaffold person name:string age:integer
rake db:migrate
  • index へのリクエスト時に Query String に age を指定することで対象 age を指定

テーブルには以下のデータが登録されています

$ select * from people;
1|tanaka|24|2014-06-25 23:45:12.555117|2014-06-25 23:45:12.555117
2|suzuki|25|2014-06-25 23:45:30.476800|2014-06-25 23:45:30.476800
3|sato||2014-06-25 23:48:59.710500|2014-06-25 23:48:59.710500

※ sato の age は null

サンプルコード

  • scaffold した状態の PeopleControllerindex メソッドを下記のように変更します
def index
  @people = Person.where.not(age: params['age'])
end

age が 24 以外のデータを検索

画面には以下のようなレコードが表示されます

suzuki san  25  Show  Edit  Destroy

age を指定しないで(nil)で検索

画面には以下のようなレコードが表示されます。

nilの分岐を作成していませんが、新たな文法により正常に表示されています。

tanaka  24  Show  Edit  Destroy
suzuki  25  Show  Edit  Destroy
6
6
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
6
6