Skip to content

Commit

Permalink
Delegate any? and many? to scoped
Browse files Browse the repository at this point in the history
  • Loading branch information
pixeltrix committed Mar 29, 2011
1 parent 827e5de commit 7f098a6
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/base.rb
Expand Up @@ -436,7 +436,8 @@ def colorize_logging(*args)
end
alias :colorize_logging= :colorize_logging

delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find, :first, :last, :all, :exists?, :any?, :many?, :to => :scoped
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
delegate :select, :group, :order, :reorder, :except, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/named_scope_test.rb
Expand Up @@ -236,6 +236,12 @@ def test_any_should_not_fire_query_if_named_scope_loaded
assert_no_queries { assert topics.any? }
end

def test_model_class_should_respond_to_any
assert Topic.any?
Topic.delete_all
assert !Topic.any?
end

def test_many_should_not_load_results
topics = Topic.base
assert_queries(2) do
Expand Down Expand Up @@ -270,6 +276,15 @@ def test_many_should_return_true_if_more_than_one
assert Topic.base.many?
end

def test_model_class_should_respond_to_many
Topic.delete_all
assert !Topic.many?
Topic.create!
assert !Topic.many?
Topic.create!
assert Topic.many?
end

def test_should_build_on_top_of_named_scope
topic = Topic.approved.build({})
assert topic.approved
Expand Down
20 changes: 20 additions & 0 deletions railties/guides/source/active_record_querying.textile
Expand Up @@ -800,6 +800,26 @@ Client.exists?

The above returns +false+ if the +clients+ table is empty and +true+ otherwise.

You can also use +any?+ and +many?+ to check for existence on a model or relation.

<ruby>
# via a model
Post.any?
Post.many?

# via a named scope
Post.recent.any?
Post.recent.many?

# via a relation
Post.where(:published => true).any?
Post.where(:published => true).many?

# via an association
Post.first.categories.any?
Post.first.categories.many?
</ruby>

h3. Calculations

This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
Expand Down

0 comments on commit 7f098a6

Please sign in to comment.