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

  • #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 14

def initialize(scope)
  @scope = scope
end

Instance Method Details

#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 name != 'Jon' AND role != 'admin'
[ GitHub ]

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

def not(opts, *rest)
  where_value = @scope.send(:build_where, opts, rest).map do |rel|
    case rel
    when NilClass
      raise ArgumentError, 'Invalid argument for .where.not(), got nil.'
    when Arel::Nodes::In
      Arel::Nodes::NotIn.new(rel.left, rel.right)
    when Arel::Nodes::Equality
      Arel::Nodes::NotEqual.new(rel.left, rel.right)
    when String
      Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
    else
      Arel::Nodes::Not.new(rel)
    end
  end

  @scope.references!(PredicateBuilder.references(opts)) if Hash === opts
  @scope.where_values += where_value
  @scope
end