Rails 7 adds ActiveRecord::Relation#excluding

Ashik Salman

Ashik Salman

March 16, 2021

This blog is part of our  Rails 7 series.

We might have used Array#excluding method to return an array after eliminating specific elements which are passed as an argument.

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

When it comes to active record queries, we usually make use of NOT condition query to eliminate specific records from the result.

=> 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.

=> 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.

=> 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.

=> 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 & 41465 for more details.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.