mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Ensure NamedScope#any? uses COUNT query wherever possible. [#680 state:resolved]
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
parent
2681685450
commit
93e10f9911
2 changed files with 31 additions and 1 deletions
|
@ -103,7 +103,7 @@ module ActiveRecord
|
|||
attr_reader :proxy_scope, :proxy_options
|
||||
|
||||
[].methods.each do |m|
|
||||
unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/
|
||||
unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?|any?)/
|
||||
delegate m, :to => :proxy_found
|
||||
end
|
||||
end
|
||||
|
@ -140,6 +140,14 @@ module ActiveRecord
|
|||
@found ? @found.empty? : count.zero?
|
||||
end
|
||||
|
||||
def any?
|
||||
if block_given?
|
||||
proxy_found.any? { |*block_args| yield(*block_args) }
|
||||
else
|
||||
!empty?
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
def proxy_found
|
||||
@found || load_found
|
||||
|
|
|
@ -184,6 +184,28 @@ class NamedScopeTest < ActiveRecord::TestCase
|
|||
end
|
||||
end
|
||||
|
||||
def test_any_should_not_load_results
|
||||
topics = Topic.base
|
||||
assert_queries(1) do
|
||||
topics.expects(:empty?).returns(true)
|
||||
assert !topics.any?
|
||||
end
|
||||
end
|
||||
|
||||
def test_any_should_call_proxy_found_if_using_a_block
|
||||
topics = Topic.base
|
||||
assert_queries(1) do
|
||||
topics.expects(:empty?).never
|
||||
topics.any? { true }
|
||||
end
|
||||
end
|
||||
|
||||
def test_any_should_not_fire_query_if_named_scope_loaded
|
||||
topics = Topic.base
|
||||
topics.collect # force load
|
||||
assert_no_queries { assert topics.any? }
|
||||
end
|
||||
|
||||
def test_should_build_with_proxy_options
|
||||
topic = Topic.approved.build({})
|
||||
assert topic.approved
|
||||
|
|
Loading…
Reference in a new issue