Class: ActiveRecord::QueryMethods::WhereChain

Inherits:
Object
  • Object
show all
Includes:
WhereChainSharedMethods
Defined in:
lib/active_record/where_chain_extensions_rails4.rb,
lib/active_record/where_chain_extensions_rails5.rb

Instance Method Summary collapse

Instance Method Details

#not(opts = :chain, *rest) ⇒ Object

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

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

If there is no argument, chain further.

User.where.not.gt(login_count: 3)
# SELECT * FROM users WHERE NOT(users.login_count > 3)

Note: This is the Active Record 5 version.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/active_record/where_chain_extensions_rails4.rb', line 18

def not(opts = :chain, *rest)
  where_value = @scope.send(:build_where, opts, rest).map do |rel|
    case rel
    when :chain
      @invert = true
      return self
    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