結論
- 条件に合致するレコードが1件以上存在するかどうかを確認したい場合
-
exists?
メソッドを使う
-
- 条件に合致するレコードが1件も存在しないかどうかを確認したい場合
-
empty?
メソッドを使う
-
使用データ
irb(main):001> ExternalUser.all
ExternalUser Load (2.1ms) SELECT `external_users`.* FROM `external_users`
=>
[#<ExternalUser:0x0000000109a00000
id: 1,
name: "external_user_1",
email: "external_user_1@example.com",
created_at: Tue, 16 Apr 2024 16:30:12.429205000 JST +09:00,
updated_at: Tue, 16 Apr 2024 16:30:12.429205000 JST +09:00>]
実行結果
present?
irb(main):001> ExternalUser.all.present?
TRANSACTION (0.1ms) BEGIN
ExternalUser Load (1.5ms) SELECT `external_users`.* FROM `external_users`
=> true
exists?
irb(main):001> ExternalUser.all.exists?
ExternalUser Exists? (0.7ms) SELECT 1 AS one FROM `external_users` LIMIT 1
=> true
blank?
irb(main):001> ExternalUser.all.blank?
ExternalUser Load (1.2ms) SELECT `external_users`.* FROM `external_users`
=> false
empty?
irb(main):001> SESEvent.all.empty?
SESEvent Exists? (1.1ms) SELECT 1 AS one FROM `ses_events` LIMIT 1
=> true