Skip to content

Commit 517f709

Browse files
committed
Properly cache association_collection#scopes calls having arguments
1 parent 3a066e8 commit 517f709

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

activerecord/lib/active_record/associations/association_collection.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,8 @@ def method_missing(method, *args)
411411
end
412412
elsif @reflection.klass.scopes[method]
413413
@_named_scopes_cache ||= {}
414-
@_named_scopes_cache[method] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
414+
@_named_scopes_cache[method] ||= {}
415+
@_named_scopes_cache[method][args] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
415416
else
416417
with_scope(construct_scope) do
417418
if block_given?

activerecord/test/cases/named_scope_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,19 @@ def test_named_scopes_are_cached_on_associations
428428
assert_no_queries { post.comments.containing_the_letter_e.all }
429429
end
430430

431+
def test_named_scopes_with_arguments_are_cached_on_associations
432+
post = posts(:welcome)
433+
434+
one = post.comments.limit_by(1).all
435+
assert_equal 1, one.size
436+
437+
two = post.comments.limit_by(2).all
438+
assert_equal 2, two.size
439+
440+
assert_no_queries { post.comments.limit_by(1).all }
441+
assert_no_queries { post.comments.limit_by(2).all }
442+
end
443+
431444
def test_named_scopes_are_reset_on_association_reload
432445
post = posts(:welcome)
433446

activerecord/test/models/comment.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
class Comment < ActiveRecord::Base
2+
scope :limit_by, lambda {|l| limit(l) }
23
scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'"
34
scope :for_first_post, :conditions => { :post_id => 1 }
45
scope :for_first_author,

0 commit comments

Comments
 (0)