Method: ActiveRecord::QueryMethods#excluding
- Defined in:
- activerecord/lib/active_record/relation/query_methods.rb
#excluding(*records) ⇒ Object Also known as: without
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.
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 |
# File 'activerecord/lib/active_record/relation/query_methods.rb', line 1574 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 |