This project is archived and is in readonly mode.

#1500 ✓resolved
Chris Kampmeier

Named scopes should implement #many? so they'll use COUNT(*)

Reported by Chris Kampmeier | December 1st, 2008 @ 06:15 AM | in 2.x

Enumerable#many? went in recently, and it's nice to have. However, many Enumerable methods have corresponding implementations in the ActiveRecord::NamedScope::Scope class, so that named scopes will do the right thing w/ SQL instead of just loading an entire collection and then sending the Enumerable method.


class User < ActiveRecord::Base
  named_scope :first_half, :conditions => ["name < ?", "N"]

>> User.first_half.many?
#  User Load (0.6ms)   SELECT * FROM "users" WHERE (name < 'N')
=> true

With this patch:

>> User.first_half.many?
#  SQL (0.1ms)   SELECT count(*) AS count_all FROM "users" WHERE (name < 'N')
=> true

Much better!

Just like #any?, it'll load the collection instead of using COUNT(*) when you use a block:

>> User.first_half.many? { |user|'A') }
#  User Load (0.4ms)   SELECT * FROM "users" WHERE (name < 'N')
=> false

That's about it, let me know what you think.

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=""></a>

Referenced by