This project is archived and is in readonly mode.
Optimization to not hit the db when preloading empty association sets
-
RSL
Optimized patch in preload_belongs_to_association method.
-
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 endwhich 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
Oops. Forgot the find that generated the SQL:
@@@ User.first :include => :current_membership
-
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)
-
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...
