Rails 7
adds
#excluding
method for an ActiveRecord::Relation
to exclude specific record (or collection of records)
from the resulting relation.
We come across cases in our Rails application, where we need to exclude a few set of records
when fetching data.
In such cases, we can use the excluding
method to filter out unwanted records.
Before
Rails 4.0 added where.not
to exclude a record or set of records from queries.
We pass our exclude conditions in the not
clause.
To ignore a particular post with a specific id we can use the below query.
To ignore the collection of records we can pass our condition in the not
clause as below.
where.not
can also be used on associations.
Let’s say we have Post
and Comment
models.
We want to ignore few comments on a particular post.
We chain where.not
clause to post.comments
query as shown below.
After
Rails 7 added #excluding
method which serves the same purpose as where.not
.
But unlike where.not
we pass objects to the excluding
method instead of object attributes.
To ignore a particular post with a specific id we can use the below query.
To exclude the collection of posts we can pass its objects to the excluding
method as below
Similar to where.not
we can use excluding
on associations as shown below
When no condition is passed to the excluding
clause it returns all records.
NOTE
An ArgumentError will be raised if either no records are specified, or if any of the records in the collection (if a collection is passed in) are not instances of the same model that the relation is scoping.
We can also use the alias method #without
in-place of #excluding
.