Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Optimization to not hit the db when preloading empty association sets

#1027

Current code hits the db whether there's any ids to preload or not. Optimization to only hit db when the ids array is not empty. Passes all current tests but I'm not sure how to make a test using Test::Unit which asserts that the database isn't hit. Could add tests with mocha if needed.

Reported by RSL · September 11th, 2008 @ 07:20 PM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. RSL
    RSL

    Optimized patch in preload_belongs_to_association method.

    September 15th, 2008 @ 07:10 PM

  2. RSL
    RSL

    Here's the case where I discovered this behavior:

    
    class User < ActiveRecord::Base
      has_many :memberships
      has_many :sites, :through => :memberships
      belongs_to :current_membership, :class_name => "Membership"
    end
    
    class Membership < ActiveRecord::Base
      belongs_to :user
      belongs_to :site
    end
    
    class Site < ActiveRecord::Base
      has_many :memberships
      has_many :users, :through => :memberships
    end
    

    which generates the following SQL:

    
      User Load (0.3ms)   SELECT * FROM `users` LIMIT 1
      Membership Columns (2.2ms)   SHOW FIELDS FROM `memberships`
      Membership Load (0.2ms)   SELECT * FROM `memberships` WHERE (`memberships`.`id` = NULL)
    

    September 15th, 2008 @ 07:15 PM

  3. RSL
    RSL

    Oops. Forgot the find that generated the SQL:

    @@@ User.first :include => :current_membership

    
    

    September 15th, 2008 @ 07:16 PM

  4. Frederick Cheung
    Frederick Cheung

    Here's my take. assert_queries does the job nicely for testing this - there was an existing case that tested the previous behaviour for belongs_to. There is actually no need to do this for the has_many etc... cases, since we check earlier on that we have at least one record (belongs_to is different because you can have records but still have no associations to load if the foreign keys are all null)

    December 14th, 2008 @ 11:04 PM

  5. Repository
    Repository
    • State changed from new to resolved

    (from [707d0dd3e1e8df7771073670e4257d933d2818f9]) Fix preloading of belongs_to with null foreign key generating useless query [#1027 Optimization to not hit the db when preloading empty association sets state:resolved] http://github.com/rails/rails/co...

    December 18th, 2008 @ 07:22 PM