This project is archived and is in readonly mode.

#1027 ✓resolved
RSL

Optimization to not hit the db when preloading empty association sets

Reported by RSL | September 11th, 2008 @ 07:20 PM | in 2.x

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.

Comments and changes to this ticket

  • RSL

    RSL September 15th, 2008 @ 07:10 PM

    Optimized patch in preload_belongs_to_association method.

  • RSL

    RSL September 15th, 2008 @ 07:15 PM

    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)
    
  • RSL

    RSL September 15th, 2008 @ 07:16 PM

    Oops. Forgot the find that generated the SQL:

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

    
    
  • Frederick Cheung

    Frederick Cheung December 14th, 2008 @ 11:04 PM

    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)

  • Repository

    Repository December 18th, 2008 @ 07:22 PM

    • State changed from “new” to “resolved”

    (from [707d0dd3e1e8df7771073670e4257d933d2818f9]) Fix preloading of belongs_to with null foreign key generating useless query [#1027 state:resolved] http://github.com/rails/rails/co...

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Referenced by

Pages