This project is archived and is in readonly mode.

#730 ✓resolved
Brad Sumersford

Named Scope does not respond to array method find_all

Reported by Brad Sumersford | July 31st, 2008 @ 03:36 PM | in 2.x

When calling find_all on a named_scope the method is not delegated to proxy_found (the actual collection) as expected. Instead is is delegated to the proxy_scope which results in a NoMethodError.

Calling .to_a on the scope explicitly works around this problem.

Example:


Topic.base.find_all(&:approved) # => NoMethodError: undefined method `find_all' for #<Class:0x19a0fb4>

Topic.base.to_a.find_all(&:approved) # => [#<Reply:0x179e720>#<Topic:0x179e388>#<Reply:0x179e20c>]

Test:

rake test_mysql TEST=test/cases/named_scope_test.rb

=> 1) Failure:

=> test_should_delegate_all_array_methods_not_defined_on_proxy_scope(NamedScopeTest)

=> Named Scope does not respond to find_all.


class NamedScopeTest < ActiveRecord::TestCase
  def test_should_delegate_all_array_methods_not_defined_on_proxy_scope
    [].methods.each do |m|
      begin # testing all methods that do not get delegated, if proxy_scope does not handle it, then it should have been delegated
        Topic.base.send m if m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/
      rescue Exception => e
        assert !$!.is_a?(NoMethodError), "Named Scope does not respond to #{m}"
      end
    end
  end
end

Possible Hackish Fix (probably better to update the regex to let find_all get delegated):


class Scope
      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?)/
          delegate m, :to => :proxy_found
        end
      end

      delegate :scopes, :with_scope, :to => :proxy_scope
+     delegate :find_all, :to => :proxy_found

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Referenced by

Pages