Skip to content

Commit 2938754

Browse files
committed
Created an unscope method for removing relations from a chain of
relations. Specific where values can be unscoped, and the unscope method still works when relations are merged or combined.
1 parent 9ee6f3c commit 2938754

4 files changed

Lines changed: 275 additions & 0 deletions

File tree

‎activerecord/CHANGELOG.md‎

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

3+
* Added functionality to unscope relations in a relations chain. For
4+
instance, if you are passed in a chain of relations as follows:
5+
6+
Posts.select(:name => "John").order('id DESC')
7+
8+
but you want to get rid of order, then this feature allows you to do:
9+
10+
Posts.select(:name => "John").order("id DESC").unscope(:order)
11+
== Posts.select(:name => "John")
12+
13+
The .unscope() function is more general than the .except() method because
14+
.except() only works on the relation it is acting on. However, .unscope()
15+
works for any relation in the entire relation chain.
16+
17+
*John Wang*
18+
319
* Postgresql timestamp with time zone (timestamptz) datatype now returns a
420
ActiveSupport::TimeWithZone instance instead of a string
521

‎activerecord/lib/active_record/relation/query_methods.rb‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,67 @@ def reorder!(*args) # :nodoc:
317317
self
318318
end
319319

320+
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
321+
:limit, :offset, :joins, :includes, :from,
322+
:readonly, :having])
323+
324+
# Removes an unwanted relation that is already defined on a chain of relations.
325+
# This is useful when passing around chains of relations and would like to
326+
# modify the relations without reconstructing the entire chain.
327+
#
328+
# User.all.order('email DESC').unscope(:order) == User.all
329+
#
330+
# The method arguments are symbols which correspond to the names of the methods
331+
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
332+
# The method can also be called with multiple arguments. For example:
333+
#
334+
# User.all.order('email DESC').select('id').where(:name => "John")
335+
# .unscope(:order, :select, :where) == User.all
336+
#
337+
# One can additionally pass a hash as an argument to unscope specific :where values.
338+
# This is done by passing a hash with a single key-value pair. The key should be
339+
# :where and the value should be the where value to unscope. For example:
340+
#
341+
# User.all.where(:name => "John", :active => true).unscope(:where => :name)
342+
# == User.all.where(:active => true)
343+
#
344+
# Note that this method is more generalized than ActiveRecord::SpawnMethods#except
345+
# because #except will only affect a particular relation's values. It won't wipe
346+
# the order, grouping, etc. when that relation is merged. For example:
347+
#
348+
# Post.comments.except(:order)
349+
#
350+
# will still have an order if it comes from the default_scope on Comment.
351+
def unscope(*args)
352+
check_if_method_has_arguments!("unscope", args)
353+
spawn.unscope!(*args)
354+
end
355+
356+
def unscope!(*args)
357+
args.flatten!
358+
359+
args.each do |scope|
360+
case scope
361+
when Symbol
362+
symbol_unscoping(scope)
363+
when Hash
364+
scope.each do |key, target_value|
365+
if key != :where
366+
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
367+
end
368+
369+
Array(target_value).each do |val|
370+
where_unscoping(val)
371+
end
372+
end
373+
else
374+
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
375+
end
376+
end
377+
378+
self
379+
end
380+
320381
# Performs a joins on +args+:
321382
#
322383
# User.joins(:posts)
@@ -762,6 +823,39 @@ def build_arel
762823

763824
private
764825

826+
def symbol_unscoping(scope)
827+
if !VALID_UNSCOPING_VALUES.include?(scope)
828+
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
829+
end
830+
831+
single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
832+
unscope_code = :"#{scope}_value#{'s' unless single_val_method}="
833+
834+
case scope
835+
when :order
836+
self.send(:reverse_order_value=, false)
837+
result = []
838+
else
839+
result = [] unless single_val_method
840+
end
841+
842+
self.send(unscope_code, result)
843+
end
844+
845+
def where_unscoping(target_value)
846+
target_value_sym = target_value.to_sym
847+
848+
where_values.reject! do |rel|
849+
case rel
850+
when Arel::Nodes::In, Arel::Nodes::Equality
851+
subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
852+
subrelation.name.to_sym == target_value_sym
853+
else
854+
raise "unscope(where: #{target_value.inspect}) failed: unscoping #{rel.class} is unimplemented."
855+
end
856+
end
857+
end
858+
765859
def custom_join_ast(table, joins)
766860
joins = joins.reject { |join| join.blank? }
767861

‎activerecord/test/cases/relation_scoping_test.rb‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,150 @@ def test_order_after_reorder_combines_orders
424424
assert_equal expected, received
425425
end
426426

427+
def test_unscope_overrides_default_scope
428+
expected = Developer.all.collect { |dev| [dev.name, dev.id] }
429+
received = Developer.order('name ASC, id DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
430+
assert_equal expected, received
431+
end
432+
433+
def test_unscope_after_reordering_and_combining
434+
expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
435+
received = DeveloperOrderedBySalary.reorder('name DESC').unscope(:order).order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
436+
assert_equal expected, received
437+
438+
expected_2 = Developer.all.collect { |dev| [dev.name, dev.id] }
439+
received_2 = Developer.order('id DESC, name DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
440+
assert_equal expected_2, received_2
441+
442+
expected_3 = Developer.all.collect { |dev| [dev.name, dev.id] }
443+
received_3 = Developer.reorder('name DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
444+
assert_equal expected_3, received_3
445+
end
446+
447+
def test_unscope_with_where_attributes
448+
expected = Developer.order('salary DESC').collect { |dev| dev.name }
449+
received = DeveloperOrderedBySalary.where(name: 'David').unscope(where: :name).collect { |dev| dev.name }
450+
assert_equal expected, received
451+
452+
expected_2 = Developer.order('salary DESC').collect { |dev| dev.name }
453+
received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({:where => :name}, :select).collect { |dev| dev.name }
454+
assert_equal expected_2, received_2
455+
456+
expected_3 = Developer.order('salary DESC').collect { |dev| dev.name }
457+
received_3 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope(:select, :where).collect { |dev| dev.name }
458+
assert_equal expected_3, received_3
459+
end
460+
461+
def test_unscope_multiple_where_clauses
462+
expected = Developer.order('salary DESC').collect { |dev| dev.name }
463+
received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect { |dev| dev.name }
464+
assert_equal expected, received
465+
end
466+
467+
def test_unscope_with_grouping_attributes
468+
expected = Developer.order('salary DESC').collect { |dev| dev.name }
469+
received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect { |dev| dev.name }
470+
assert_equal expected, received
471+
472+
expected_2 = Developer.order('salary DESC').collect { |dev| dev.name }
473+
received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect { |dev| dev.name }
474+
assert_equal expected_2, received_2
475+
end
476+
477+
def test_unscope_with_limit_in_query
478+
expected = Developer.order('salary DESC').collect { |dev| dev.name }
479+
received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect { |dev| dev.name }
480+
assert_equal expected, received
481+
end
482+
483+
def test_order_to_unscope_reordering
484+
expected = DeveloperOrderedBySalary.all.collect { |dev| [dev.name, dev.id] }
485+
received = DeveloperOrderedBySalary.order('salary DESC, name ASC').reverse_order.unscope(:order).collect { |dev| [dev.name, dev.id] }
486+
assert_equal expected, received
487+
end
488+
489+
def test_unscope_reverse_order
490+
expected = Developer.all.collect { |dev| dev.name }
491+
received = Developer.order('salary DESC').reverse_order.unscope(:order).collect { |dev| dev.name }
492+
assert_equal expected, received
493+
end
494+
495+
def test_unscope_select
496+
expected = Developer.order('salary ASC').collect { |dev| dev.name }
497+
received = Developer.order('salary DESC').reverse_order.select(:name => "Jamis").unscope(:select).collect { |dev| dev.name }
498+
assert_equal expected, received
499+
500+
expected_2 = Developer.all.collect { |dev| dev.id }
501+
received_2 = Developer.select(:name).unscope(:select).collect { |dev| dev.id }
502+
assert_equal expected_2, received_2
503+
end
504+
505+
def test_unscope_offset
506+
expected = Developer.all.collect { |dev| dev.name }
507+
received = Developer.offset(5).unscope(:offset).collect { |dev| dev.name }
508+
assert_equal expected, received
509+
end
510+
511+
def test_unscope_joins_and_select_on_developers_projects
512+
expected = Developer.all.collect { |dev| dev.name }
513+
received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect { |dev| dev.name }
514+
assert_equal expected, received
515+
end
516+
517+
def test_unscope_includes
518+
expected = Developer.all.collect { |dev| dev.name }
519+
received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect { |dev| dev.name }
520+
assert_equal expected, received
521+
end
522+
523+
def test_unscope_having
524+
expected = DeveloperOrderedBySalary.all.collect { |dev| dev.name }
525+
received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect { |dev| dev.name }
526+
assert_equal expected, received
527+
end
528+
529+
def test_unscope_errors_with_invalid_value
530+
assert_raises(ArgumentError) do
531+
Developer.includes(:projects).where(name: "Jamis").unscope(:stupidly_incorrect_value)
532+
end
533+
534+
assert_raises(ArgumentError) do
535+
Developer.all.unscope(:includes, :select, :some_broken_value)
536+
end
537+
538+
assert_raises(ArgumentError) do
539+
Developer.order('name DESC').reverse_order.unscope(:reverse_order)
540+
end
541+
542+
assert_raises(ArgumentError) do
543+
Developer.order('name DESC').where(name: "Jamis").unscope()
544+
end
545+
end
546+
547+
def test_unscope_errors_with_non_where_hash_keys
548+
assert_raises(ArgumentError) do
549+
Developer.where(name: "Jamis").limit(4).unscope(limit: 4)
550+
end
551+
552+
assert_raises(ArgumentError) do
553+
Developer.where(name: "Jamis").unscope("where" => :name)
554+
end
555+
end
556+
557+
def test_unscope_errors_with_non_symbol_or_hash_arguments
558+
assert_raises(ArgumentError) do
559+
Developer.where(name: "Jamis").limit(3).unscope("limit")
560+
end
561+
562+
assert_raises(ArgumentError) do
563+
Developer.select("id").unscope("select")
564+
end
565+
566+
assert_raises(ArgumentError) do
567+
Developer.select("id").unscope(5)
568+
end
569+
end
570+
427571
def test_order_in_default_scope_should_not_prevail
428572
expected = Developer.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
429573
received = DeveloperOrderedBySalary.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }

‎guides/source/active_record_querying.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,27 @@ The SQL that would be executed:
692692
SELECT * FROM posts WHERE id > 10 LIMIT 20
693693
```
694694

695+
### `unscope`
696+
697+
The `except` method does not work when the relation is merged. For example:
698+
699+
```ruby
700+
Post.comments.except(:order)
701+
```
702+
703+
will still have an order if the order comes from a default scope on Comment. In order to remove all ordering, even from relations which are merged in, use unscope as follows:
704+
705+
```ruby
706+
Post.order('id DESC').limit(20).unscope(:order) = Post.limit(20)
707+
Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all
708+
```
709+
710+
You can additionally unscope specific where clauses. For example:
711+
712+
```ruby
713+
Post.where(:id => 10).limit(1).unscope(:where => :id, :limit).order('id DESC') = Post.order('id DESC')
714+
```
715+
695716
### `only`
696717

697718
You can also override conditions using the `only` method. For example:

0 commit comments

Comments
 (0)