Skip to content

Commit f1082b8

Browse files
committed
Merge pull request rails#9553 from neerajdotname/7365-mergin-scopes-and-where
7365 merging scopes for where clauses
2 parents b670433 + cd26b6a commit f1082b8

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

activerecord/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
## Rails 4.0.0 (unreleased) ##
22

3+
* Previously `Post.active.inactive` used to result in `Post.inactive`
4+
since the last where clause used to win while combining scopes.
5+
Now all the scopes will be merged using `AND`. Fixes #7365 .
6+
7+
*Neeraj Singh* and *Jon Leighton*
8+
39
* Expand `#cache_key` to consult all relevant updated timestamps.
410

511
Previously only `updated_at` column was checked, now it will

activerecord/lib/active_record/scoping/named.rb

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,20 @@ def scope(name, body, &block)
159159
end
160160

161161
singleton_class.send(:define_method, name) do |*args|
162-
options = body.respond_to?(:call) ? unscoped { body.call(*args) } : body
163-
relation = all.merge(options)
162+
if body.respond_to?(:call)
163+
scope = extension ? body.call(*args).extending(extension) : body.call(*args)
164164

165-
extension ? relation.extending(extension) : relation
165+
if scope
166+
default_scoped = scope.default_scoped
167+
scope = relation.merge(scope)
168+
scope.default_scoped = default_scoped
169+
end
170+
171+
else
172+
scope = body
173+
end
174+
175+
scope || all
166176
end
167177
end
168178
end

activerecord/test/cases/named_scope_test.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,11 +325,11 @@ def test_chaining_should_use_latest_conditions_when_creating
325325

326326
def test_chaining_should_use_latest_conditions_when_searching
327327
# Normal hash conditions
328-
assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.to_a
329-
assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.to_a
328+
assert_equal Topic.where(approved: false).where(approved: true).to_a, Topic.rejected.approved.to_a
329+
assert_equal Topic.where(approved: true).where(approved: false).to_a, Topic.approved.rejected.to_a
330330

331331
# Nested hash conditions with same keys
332-
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.to_a
332+
assert_equal [], Post.with_special_comments.with_very_special_comments.to_a
333333

334334
# Nested hash conditions with different keys
335335
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).to_a.uniq

0 commit comments

Comments
 (0)