-
Notifications
You must be signed in to change notification settings - Fork 186
Open
Description
Environment
- Ruby 3.2.2
- Rails 7.1.1
- ActiveHash 3.2.1
Problem
When accessing a belongs_to
association, if the related id is missing then a query for id IS NULL
is made. This is different from the standard ActiveRecord behaviour and I think in 99% of cases a redundant query. Seems to be caused by the internal use of find_by_id
with a blank argument: https://github.com/active-hash/active_hash/blob/master/lib/associations/associations.rb#L177
You can reproduce and observe with this script:
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", "7.1.1"
gem "sqlite3"
gem "active_hash", "3.2.1"
end
require "active_hash"
require "active_record"
require "logger"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "db/development.sqlite3")
ActiveRecord::Schema.define do
create_table :authors, force: true
create_table :magazines, force: true do |t|
t.belongs_to :author, null: true
end
end
class Author < ActiveRecord::Base
end
class Book < ActiveHash::Base
include ActiveHash::Associations
fields :author_id
belongs_to :author
end
class Magazine < ActiveRecord::Base
belongs_to :author, optional: true
end
book = Book.new(author_id: nil)
magazine = Magazine.create!(author_id: nil)
ActiveRecord::Base.logger = Logger.new(STDOUT)
puts "-" * 50
puts "Accessing ActiveHash association with NULL key"
book.author
puts "-" * 50
puts "Accessing ActiveRecord association with NULL key"
magazine.author
puts "-" * 50
Potential Solution
Don't bother querying if the key is NULL, if there is some weird edge case where you would want this then perhaps the behaviour could be enabled with a config option or optional argument when defining the association.
Metadata
Metadata
Assignees
Labels
No labels