---
title: "Rails 7 adds ActiveRecord::Relation#excluding"
description: "Rails 7.0 adds ActiveRecord::Relation#excluding"
canonical_url: "https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding"
markdown_url: "https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding.md"
---

# Rails 7 adds ActiveRecord::Relation#excluding

Rails 7.0 adds ActiveRecord::Relation#excluding

- Author: Ashik Salman
- Published: March 16, 2021
- Categories: Rails, Rails 7

We might have used
[Array#excluding](https://www.rubydoc.info/docs/rails/Array:excluding) method to
return an array after eliminating specific elements which are passed as an
argument.

```ruby
=> ["John", "Sam", "Oliver"].excluding("Sam")
=> ["John", "Oliver"]
```

When it comes to active record queries, we usually make use of
[NOT condition](https://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)
query to eliminate specific records from the result.

```ruby
=> users = User.where.not(id: current_user.id)
=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" != 1"
```

This is simplified with Rails 7's newly-introduced
`ActiveRecord::Relation#excluding` method.

```ruby
=> users = User.excluding(current_user)
=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" != 1"

# We can also pass a collection of records as an argument

=> comments = Comment.excluding(current_user.comments)
=> "SELECT \"comments\".* FROM \"comments\" WHERE \"comments\".\"id\" NOT IN (1, 2)"
```

The excluding method applies to activerecord association as well.

```ruby
=> comments = current_user.comments.excluding(comment1, comment2)
=> "SELECT \"comments\".* FROM \"comments\" WHERE \"comments\".\"user_id\" = 1 AND \"comments\".\"id\" NOT IN (1, 2)"
```

The alias method `without` can also be used instead of `excluding`.

```ruby
=> users = User.without(current_user)
=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" != 1"

=> comments = Comment.without(comment1)
=> "SELECT \"comments\".* FROM \"comments\" WHERE \"comments\".\"id\" != 1"
```

Check out these pull request [41439](https://github.com/rails/rails/pull/41439)
& [41465](https://github.com/rails/rails/pull/41465) for more details.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding)
