instance method excluding

Ruby on Rails 8.1.2

Since v7.0.10

Available in: v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

excluding(*records)

Excludes the specified record (or collection of records) from the resulting relation. For example:

Post.excluding(post)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" != 1

Post.excluding(post_one, post_two)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" NOT IN (1, 2)

Post.excluding(Post.drafts)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" NOT IN (3, 4, 5)

This can also be called on associations. As with the above example, either a single record of collection thereof may be specified:

post = Post.find(1)
comment = Comment.find(2)
post.comments.excluding(comment)
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 AND "comments"."id" != 2

This is short-hand for .where.not(id: post.id) and .where.not(id: [post_one.id, post_two.id]).

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.

Parameters

records rest
Source
# File activerecord/lib/active_record/relation/query_methods.rb, line 1575
    def excluding(*records)
      relations = records.extract! { |element| element.is_a?(Relation) }
      records.flatten!(1)
      records.compact!

      unless records.all?(model) && relations.all? { |relation| relation.model == model }
        raise ArgumentError, "You must only pass a single or collection of #{model.name} objects to ##{__callee__}."
      end

      spawn.excluding!(records + relations.flat_map(&:ids))
    end

Defined in activerecord/lib/active_record/relation/query_methods.rb line 1575 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::QueryMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close