在Rails 6(使用PostgreSQL)中,当我将attr: nil
放入WHERE子句时,ActiveRecord会将1=0
放入SQL,即使数据库中存在attr
为NULL的记录
我希望它按照this answer将"attr" IS NULL
放入SQL中
只有在使用如下数组时,它才能正常工作:attr: [nil]
,这是为什么?
这就是我在Rails控制台中看到的内容:
irb(main):048:0> puts Output.where(value: nil).to_sql
SELECT "outputs".* FROM "outputs" WHERE 1=0
irb(main):049:0> puts Output.where(value: [nil]).to_sql
SELECT "outputs".* FROM "outputs" WHERE "outputs"."value" IS NULL
这是非常令人沮丧的,因为这意味着当我在where子句中使用变量时,如果变量有可能为nil,我必须记住将变量放入数组中(我总是希望nil与WHERE子句中的NULL匹配,因为ActiveRecord总是将数据库中的NULL作为nil返回给我)
Rails版本为6.0.0.beta3 6.1.4
这是我宝石文件:
ruby '2.6.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.1.4'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.11'
gem 'rails-reverse-proxy'
# create hashes from plucked data
gem 'pluck_all'
# Create DOCX files
gem 'caracal'
# Create Excel files
gem 'caxlsx'
# Read and edit Excel files
gem 'rubyXL'
# track changes in models
gem 'paper_trail'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.1', require: false
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'
# Google Cloud Storage with ActiveStorage
gem "google-cloud-storage", "~> 1.11", require: false
# Generate fake data
gem 'faker'
# easy factories for generating model instances for test and sandbox
gem 'factory_bot_rails'
# For gRPC
gem 'grpc'
gem 'grpc_for_rails'
gem 'googleapis-common-protos'
gem 'googleapis-common-protos-types'
gem 'gruf'
# To use Memcache as a cache store
gem 'dalli'
# Background processing, uses threads to handle many jobs at the same time in the same process
gem 'sidekiq'
# For converting HTML to PDF
gem 'wicked_pdf', '~> 2.0.1'
gem 'wkhtmltopdf-binary', '~> 0.12.5.4'
# For getting image dimensions
gem 'fastimage'
# For scheduling jobs
gem 'sidekiq-scheduler'
# For consuming external APIs
gem 'httparty'
1条答案
按热度按时间jfewjypa1#
我的一位同事最终发现了这是怎么回事。我们有一些代码覆盖ActiveRecord中
where
的行为,并用nil
替换[]