Why You Should Consider Using excluding Instead of where.not in ActiveRecord

In Ruby on Rails, ActiveRecord simplifies working with databases, and where.not is a common way to filter out records based on a condition. However, in some cases, using excluding — introduced in Rails 7 — can be a better alternative. Here’s why.

What is where.not?

where.not is used to exclude records that meet a specific condition. For example, if you want to fetch all users except those with a certain email:

1
User.where.not(email: 'example@domain.com')

This is useful for excluding records based on specific conditions.

What is excluding?

excluding allows you to exclude specific records from a query. For example, to fetch all users but exclude a specific user:

1
2
user_to_exclude = User.find_by(email: 'example@domain.com')
users = User.excluding(user_to_exclude)

This query retrieves all users except the one with the email example@domain.com.

Excluding Multiple Records

If you need to exclude multiple specific records, you can pass an array of records to excluding. For instance:

1
2
users_to_exclude = User.where(role: 'admin')
users = User.excluding(users_to_exclude)

This excludes all users with the role admin from the result set.

Another example of excluding multiple specific users could be:

1
2
specific_users = User.where(email: ['user1@domain.com', 'user2@domain.com'])
users = User.excluding(specific_users)

Here, users with the emails user1@domain.com and user2@domain.com are excluded from the query result.

Why Use excluding?

When to Use where.not?

Use where.not when you need to exclude entire records based on a condition, like excluding users over a certain age or with a specific status.

While where.not is great for excluding records based on conditions, excluding provides a cleaner, more intuitive way to exclude specific records. If you’re using Rails 7+, consider using excluding when working with individual records or groups of records for better readability and maintainability.