mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
When preloading group by reflection rather than by class [#125 state:resolved]
This avoids extra queries when several subclasses inherit the association from their parent class, while still coping with subclasses redefining associations. Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
parent
0cbdd96c34
commit
236f0bb67a
2 changed files with 12 additions and 6 deletions
|
@ -31,12 +31,12 @@ module ActiveRecord
|
||||||
private
|
private
|
||||||
|
|
||||||
def preload_one_association(records, association, preload_options={})
|
def preload_one_association(records, association, preload_options={})
|
||||||
reflection = reflections[association]
|
class_to_reflection = {}
|
||||||
|
# Not all records have the same class, so group then preload
|
||||||
|
# group on the reflection itself so that if various subclass share the same association then we do not split them
|
||||||
|
# unncessarily
|
||||||
|
records.group_by {|record| class_to_reflection[record.class] ||= record.class.reflections[association]}.each do |reflection, records|
|
||||||
raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection
|
raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection
|
||||||
|
|
||||||
# Not all records have the same class, so group then preload.
|
|
||||||
records.group_by(&:class).each do |klass, records|
|
|
||||||
reflection = klass.reflections[association]
|
|
||||||
send("preload_#{reflection.macro}_association", records, reflection, preload_options)
|
send("preload_#{reflection.macro}_association", records, reflection, preload_options)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -603,4 +603,10 @@ class EagerAssociationTest < ActiveRecord::TestCase
|
||||||
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15")
|
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_load_with_sti_sharing_association
|
||||||
|
assert_queries(2) do #should not do 1 query per subclass
|
||||||
|
Comment.find :all, :include => :post
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue