Permalink
Browse files

Add CollectionProxy#scope

This can be used to get a Relation from an association.

Previously we had a #scoped method, but we're deprecating that for
AR::Base, so it doesn't make sense to have it here.

This was requested by DHH, to facilitate code like this:

    Project.scope.order('created_at DESC').page(current_page).tagged_with(@tag).limit(5).scoping do
      @topics      = @project.topics.scope
      @todolists   = @project.todolists.scope
      @attachments = @project.attachments.scope
      @documents   = @project.documents.scope
    end
  • Loading branch information...
1 parent 26d3e32 commit 0e1cafcbc4d67854faf35e489571bc30f5e2ac14 @jonleighton jonleighton committed Aug 1, 2012
View
@@ -1,5 +1,23 @@
## Rails 4.0.0 (unreleased) ##
+* Add CollectionProxy#scope
+
+ This can be used to get a Relation from an association.
+
+ Previously we had a #scoped method, but we're deprecating that for
+ AR::Base, so it doesn't make sense to have it here.
+
+ This was requested by DHH, to facilitate code like this:
+
+ Project.scope.order('created_at DESC').page(current_page).tagged_with(@tag).limit(5).scoping do
+ @topics = @project.topics.scope
+ @todolists = @project.todolists.scope
+ @attachments = @project.attachments.scope
+ @documents = @project.documents.scope
+ end
+
+ *Jon Leighton*
+
* Add `Relation#load`
This method explicitly loads the records and then returns `self`.
@@ -855,14 +855,18 @@ def scoping
@association.scoped.scoping { yield }
end
- def spawn
+ # Returns a <tt>Relation</tt> object for the records in this association
+ def scope
association = @association
@association.scoped.extending! do
define_method(:proxy_association) { association }
end
end
+ # :nodoc:
+ alias spawn scope
+
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
# contain the same number of elements and if each element is equal
# to the corresponding element in the other array, otherwise returns
@@ -218,6 +218,13 @@ def test_proxy_association_accessor
def test_scoped_allows_conditions
assert developers(:david).projects.merge!(where: 'foo').where_values.include?('foo')
end
+
+ test "getting a scope from an association" do
+ david = developers(:david)
+
+ assert david.projects.scope.is_a?(ActiveRecord::Relation)
+ assert_equal david.projects, david.projects.scope
+ end
end
class OverridingAssociationsTest < ActiveRecord::TestCase

0 comments on commit 0e1cafc

Please sign in to comment.