From 891227cef8087eb8d80918001465da971a160644 Mon Sep 17 00:00:00 2001 From: vy0b0x Date: Tue, 8 Mar 2022 04:22:55 +0000 Subject: [PATCH] Improve the documentation and guide about where.not --- .../lib/active_record/relation/query_methods.rb | 7 +++++++ guides/source/active_record_querying.md | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index f4c7a77f4e..1e58a0700e 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -40,6 +40,13 @@ module ActiveRecord # # User.where.not(name: "Jon", role: "admin") # # SELECT * FROM users WHERE NOT (name == 'Jon' AND role == 'admin') + # + # If there is a non-nil condition on a nullable column in the hash condition, the records that have + # nil values on the nullable column won't be returned. + # User.create!(nullbale_country: nil) + # User.where.not(nullable_country: "UK") + # # SELECT * FROM users WHERE NOT (nullable_country = 'UK') + # # => [] def not(opts, *rest) where_clause = @scope.send(:build_where_clause, opts, rest) diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 3a7b698ca0..7fa98574d5 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -666,6 +666,18 @@ In other words, this query can be generated by calling `where` with no argument, SELECT * FROM customers WHERE (customers.orders_count NOT IN (1,3,5)) ``` +If a query has a hash condition with non-nil values on a nullable column, the records that have `nil` values on the nullable column won't be returned. For example: + +```ruby +Customer.create!(nullable_contry: nil) +Customer.where.not(nullable_country: "UK") +=> [] +# But +Customer.create!(nullable_contry: "UK") +Customer.where.not(nullable_country: nil) +=> [#] +``` + [`where.not`]: https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-not ### OR Conditions