diff options
author | Tom Stuart <tom@obsess.com> | 2008-08-29 15:11:25 +0100 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2008-08-29 22:18:49 +0100 |
commit | 7f179f8540ab92dbd9d3e650b465de5b694d93d4 (patch) | |
tree | 913eb8d2984c33f770c315c533cb339e7058d1d9 | |
parent | c0361344d95162cd8573592d60e52986eaca0377 (diff) | |
download | rails-7f179f8540ab92dbd9d3e650b465de5b694d93d4.tar.gz rails-7f179f8540ab92dbd9d3e650b465de5b694d93d4.tar.bz2 rails-7f179f8540ab92dbd9d3e650b465de5b694d93d4.zip |
Make NamedScope#size behave identically to AssociationCollection#size. [#933 state:resolved]
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
-rw-r--r-- | activerecord/lib/active_record/named_scope.rb | 6 | ||||
-rw-r--r-- | activerecord/test/cases/named_scope_test.rb | 15 |
2 files changed, 20 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 7397d70279..d7e152ed1d 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -101,7 +101,7 @@ module ActiveRecord class Scope attr_reader :proxy_scope, :proxy_options - NON_DELEGATE_METHODS = %w(nil? send object_id class extend find count sum average maximum minimum paginate first last empty? any? respond_to?).to_set + NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? respond_to?).to_set [].methods.each do |m| unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s) delegate m, :to => :proxy_found @@ -136,6 +136,10 @@ module ActiveRecord end end + def size + @found ? @found.length : count + end + def empty? @found ? @found.empty? : count.zero? end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index acc3b3016a..444debd255 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -256,4 +256,19 @@ class NamedScopeTest < ActiveRecord::TestCase def test_should_use_where_in_query_for_named_scope assert_equal Developer.find_all_by_name('Jamis'), Developer.find_all_by_id(Developer.jamises) end + + def test_size_should_use_count_when_results_are_not_loaded + topics = Topic.base + assert_queries(1) do + assert_sql(/COUNT/i) { topics.size } + end + end + + def test_size_should_use_length_when_results_are_loaded + topics = Topic.base + topics.reload # force load + assert_no_queries do + topics.size # use loaded (no query) + end + end end |