Skip to content
Browse files

Merge pull request #8413 from senny/8403_backport

backport #8403, no intermediate AR objects when eager loading.
  • Loading branch information...
2 parents dac811e + 1b96176 commit 549da0dd8f88179485b45338bea383fe61775624 @rafaelfranca rafaelfranca committed Dec 4, 2012
View
7 activerecord/CHANGELOG.md
@@ -1,5 +1,12 @@
## Rails 3.2.10 (unreleased)
+* Do not instantiate intermediate Active Record objects when eager loading.
+ These records caused `after_find` to run more than expected.
+ Fix #3313
+ Backport of #8403
+
+ *Yves Senn*
+
* Fix `pluck` to work with joins. Backport of #4942.
*Carlos Antonio da Silva*
View
6 activerecord/lib/active_record/relation/finder_methods.rb
@@ -253,9 +253,11 @@ def construct_limited_ids_condition(relation)
orders = relation.order_values.map { |val| val.presence }.compact
values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
- relation = relation.dup
+ relation = relation.dup.select(values)
+
+ id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
+ ids_array = id_rows.map {|row| row[primary_key]}
- ids_array = relation.select(values).collect {|row| row[primary_key]}
ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
end
View
6 activerecord/test/cases/associations/eager_test.rb
@@ -916,6 +916,12 @@ def test_conditions_on_join_table_with_include_and_limit
assert_equal 3, Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).size
end
+ def test_dont_create_temporary_active_record_instances
+ Developer.instance_count = 0
+ developers = Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).to_a
+ assert_equal developers.count, Developer.instance_count
+ end
+
def test_order_on_join_table_with_include_and_limit
assert_equal 5, Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size
end
View
9 activerecord/test/models/developer.rb
@@ -63,6 +63,15 @@ def self.all_johns
self.all
end
end
+
+ after_find :track_instance_count
+ cattr_accessor :instance_count
+
+ def track_instance_count
+ self.class.instance_count ||= 0
+ self.class.instance_count += 1
+ end
+ private :track_instance_count
end
class AuditLog < ActiveRecord::Base

0 comments on commit 549da0d

Please sign in to comment.
Something went wrong with that request. Please try again.