Permalink
Browse files

Allow preload and eager_load to work on relations at the same time.

  • Loading branch information...
1 parent c3b4da7 commit 1d5854826b27e5e8bfb041c57a49d1e46178b49e @miloops miloops committed Oct 7, 2009
Showing with 30 additions and 6 deletions.
  1. +8 −6 activerecord/lib/active_record/relation.rb
  2. +22 −0 activerecord/test/cases/relations_test.rb
@@ -26,9 +26,9 @@ def readonly
end
def to_a
- if @eager_load_associations.any?
- records = catch :invalid_query do
- @klass.send(:find_with_associations, {
+ records = if @eager_load_associations.any?
+ catch :invalid_query do
+ return @klass.send(:find_with_associations, {
:select => @relation.send(:select_clauses).join(', '),
:joins => @relation.joins(relation),
:group => @relation.send(:group_clauses).join(', '),
@@ -38,12 +38,14 @@ def to_a
},
ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations, nil))
end
+ []
else
- records = @klass.find_by_sql(@relation.to_sql)
- @klass.send(:preload_associations, records, @associations_to_preload) unless @associations_to_preload.empty?
- records.each { |record| record.readonly! } if @readonly
+ @klass.find_by_sql(@relation.to_sql)
end
+ @klass.send(:preload_associations, records, @associations_to_preload) unless @associations_to_preload.empty?
+ records.each { |record| record.readonly! } if @readonly
+
records
end
@@ -4,6 +4,7 @@
require 'models/comment'
require 'models/reply'
require 'models/author'
+require 'models/comment'
require 'models/entrant'
require 'models/developer'
require 'models/company'
@@ -125,5 +126,26 @@ def test_default_scope_with_conditions_hash
assert_equal 'Jamis', DeveloperCalledJamis.create!.name
end
+ def test_loading_with_one_association
+ posts = Post.all(:include => :comments).to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ post = Post.find(:first, :include => :comments, :conditions => "posts.title = 'Welcome to the weblog'")
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ posts = Post.all(:include => :last_comment).to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
+ def test_loading_with_one_association_with_non_preload
+ posts = Post.all(:include => :last_comment, :order => 'comments.id DESC').to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
end

0 comments on commit 1d58548

Please sign in to comment.