Skip to content

Accessing belongs_to association without a key creates a useless query #302

@Catsuko

Description

@Catsuko

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions