Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@massaaaaan

【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
6
Help us understand the problem. What are the problem?