This project is archived and is in readonly mode.
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 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 September 15th, 2008 @ 07:16 PM
Oops. Forgot the find that generated the SQL:
@@@ User.first :include => :current_membership
-
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 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
Attachments
Referenced by
- 1027 Optimization to not hit the db when preloading empty association sets (from [707d0dd3e1e8df7771073670e4257d933d2818f9]) Fix pre...
- 910 find(:include) will look for rows with null primary keys Same as #1027, now fixed