20
7

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.

【Ruby on Rails】ActiveRecordのexists?の逆はempty?を使う

Posted at

概要

ActiveRecordで条件に一致するデータが存在するかどうかを調べたいときは、exists?を使います。

User.where(name: "太郎").exists?
  User Exists (0.2ms)  SELECT  1 AS one FROM "users" WHERE "users"."name" = ? LIMIT ?  [["name", "太郎"], ["LIMIT", 1]]
=> true

その逆で、条件に一致するデータが存在しないことを調べたい際は先頭にnot演算子を付けるケースをよく見かけます。

!User.where(name: "太郎").exists?
  User Exists (0.2ms)  SELECT  1 AS one FROM "users" WHERE "users"."name" = ? LIMIT ?  [["name", "太郎"], ["LIMIT", 1]]
=> false

しかし、わざわざnot演算子を付けるのはなんかカッコ悪い感じがしますよね。

解決策

ActiveRecord::Relationには、レコードが0件の際にtrueを返すempty?というメソッドがあります。
実際にempty?を使って先ほどの実装を書き直してみました。

User.where(name: "太郎").empty?
  User Exists (0.2ms)  SELECT  1 AS one FROM "users" WHERE "users"."name" = ? LIMIT ?  [["name", "太郎"], ["LIMIT", 1]]
=> false

これなら!exists?のようにnot演算子を書かなくて良いので、スッキリして見えますね!

20
7
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
20
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?