NOT検索とは
条件を付してレコードを取得する際、whereを使用しますが、逆に「この条件に当てはまらないレコード」を取り出したい場合には、NOT検索を使います。
モデル名.where.not(カラム名: データ)
このように記述すると、条件に当てはまらないレコードを取り出すことができます。
参考例
[前提]name,age,genderの3つのカラムをもつUserテーブル
Userテーブルから、age => ’23’ の条件に当てはまらないレコードを取り出します。
[1] pry(main)> User.where.not(age: '23')
すると以下のように、23歳以外のレコードを取り出すことができました。
User Load (3.6ms) SELECT `users`.* FROM `users` WHERE `users`.`age` != 23
=> [#<User:0x000000012089e290 id: 2, name: "田中", age: 21, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.809896000 UTC +00:00>,
#<User:0x000000012089e150 id: 4, name: "佐藤", age: 24, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.814096000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.814096000 UTC +00:00>,
#<User:0x000000012089e088 id: 5, name: "山田", age: 22, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.815985000 UTC +00:00>,
#<User:0x000000012089df48 id: 6, name: "山田", age: 24, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.818905000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.818905000 UTC +00:00>,
#<User:0x000000012089dd40 id: 7, name: "加藤", age: 38, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.820805000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.820805000 UTC +00:00>,
#<User:0x000000012089dc00 id: 8, name: "加藤", age: 21, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.823235000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.823235000 UTC +00:00>,
#<User:0x000000012089da70 id: 10, name: "荻野", age: 38, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.826754000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.826754000 UTC +00:00>,
#<User:0x000000012089d7a0 id: 11, name: "藤原", age: 21, gender: "men", created_at: Fri, 19 Nov 2021 10:15:21.828604000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.828604000 UTC +00:00>,
#<User:0x000000012089d430 id: 12, name: "中村", age: 28, gender: "women", created_at: Fri, 19 Nov 2021 10:15:21.831359000 UTC +00:00, updated_at: Fri, 19 Nov 2021 10:15:21.831359000 UTC +00:00>]