Help us understand the problem. What is going on with this article?

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

概要

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演算子を書かなくて良いので、スッキリして見えますね!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした