From f7ac04c2cf2cb8ae4756cc9b5e42306af95028c6 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 9 Dec 2009 16:47:26 -0300 Subject: [PATCH] ActiveRecord::Relation#to_a should not load records each time is called. --- activerecord/lib/active_record/base.rb | 2 ++ activerecord/lib/active_record/relation.rb | 2 ++ activerecord/test/cases/relations_test.rb | 10 +++++++++- 3 files changed, 13 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 321bba4..62cece8 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -681,6 +681,8 @@ module ActiveRecord #:nodoc: end end end + + relation.unmemoize_all relation end diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 5f0eec7..fb44efc 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,5 +1,6 @@ module ActiveRecord class Relation + extend ActiveSupport::Memoizable delegate :to_sql, :to => :relation delegate :length, :collect, :find, :map, :each, :to => :to_a attr_reader :relation, :klass @@ -50,6 +51,7 @@ module ActiveRecord records end + memoize :to_a def first @relation = @relation.take(1) diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 1a2c803..39f204e 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -146,5 +146,13 @@ class RelationTest < ActiveRecord::TestCase post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end -end + def test_should_memoize_records + @posts = Post.all + assert_queries(1) do + 2.times do + @posts.to_a + end + end + end +end -- 1.6.5