123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::QueryMethods::WhereChain

Relationships & Source Files
Inherits: Object
Defined in: activerecord/lib/active_record/relation/query_methods.rb

Overview

WhereChain objects act as placeholder for queries in which #where does not have any parameter. In this case, #where must be chained with #not to return a new relation.

Class Method Summary

Instance Method Summary

  • #missing(*args)

    Returns a new relation with left outer joins and where clause to identify missing relations.

  • #not(opts, *rest)

    Returns a new relation expressing WHERE + NOT condition according to the conditions in the arguments.

Constructor Details

.new(scope) ⇒ WhereChain

[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/query_methods.rb', line 18

def initialize(scope)
  @scope = scope
end

Instance Method Details

#missing(*args)

Returns a new relation with left outer joins and where clause to identify missing relations.

For example, posts that are missing a related author:

Post.where.missing(:author)
# SELECT "posts".* FROM "posts"
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# WHERE "authors"."id" IS NULL

Additionally, multiple relations can be combined. This will return posts that are missing both an author and any comments:

Post.where.missing(:author, :comments)
# SELECT "posts".* FROM "posts"
# LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
# WHERE "authors"."id" IS NULL AND "comments"."id" IS NULL
[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/query_methods.rb', line 71

def missing(*args)
  args.each do |arg|
    reflection = @scope.klass._reflect_on_association(arg)
    opts = { reflection.table_name => { reflection.association_primary_key => nil } }
    @scope.left_outer_joins!(arg)
    @scope.where!(opts)
  end

  @scope
end

#not(opts, *rest)

Returns a new relation expressing WHERE + NOT condition according to the conditions in the arguments.

#not accepts conditions as a string, array, or hash. See ActiveRecord::QueryMethods#where for more details on each format.

User.where.not("name = 'Jon'")
# SELECT * FROM users WHERE NOT (name = 'Jon')

User.where.not(["name = ?", "Jon"])
# SELECT * FROM users WHERE NOT (name = 'Jon')

User.where.not(name: "Jon")
# SELECT * FROM users WHERE name != 'Jon'

User.where.not(name: nil)
# SELECT * FROM users WHERE name IS NOT NULL

User.where.not(name: %w(Ko1 Nobu))
# SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')

User.where.not(name: "Jon", role: "admin")
# SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin')
[ GitHub ]

  
# File 'activerecord/lib/active_record/relation/query_methods.rb', line 45

def not(opts, *rest)
  where_clause = @scope.send(:build_where_clause, opts, rest)

  @scope.where_clause += where_clause.invert

  @scope
end