Skip to content

Commit

Permalink
Merge pull request #29461 from dnl/unscope_where_or
Browse files Browse the repository at this point in the history
Don't require 'unscope' to be the same on both sides of an 'or' relation
  • Loading branch information
matthewd committed Jun 17, 2017
2 parents fca22ba + 532125a commit c295296
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/relation/query_methods.rb
Expand Up @@ -1167,7 +1167,7 @@ def check_if_method_has_arguments!(method_name, args)
end
end

STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having]
STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having, :unscope]
def structurally_incompatible_values_for_or(other)
STRUCTURAL_OR_METHODS.reject do |method|
get_value(method) == other.get_value(method)
Expand Down
25 changes: 25 additions & 0 deletions activerecord/test/cases/relation/or_test.rb
Expand Up @@ -59,6 +59,31 @@ def test_or_with_incompatible_relations
assert_equal "Relation passed to #or must be structurally compatible. Incompatible values: [:order]", error.message
end

def test_or_with_unscope_where
expected = Post.where("id = 1 or id = 2")
partial = Post.where("id = 1 and id != 2")
assert_equal expected, partial.or(partial.unscope(:where).where("id = 2")).to_a
end

def test_or_with_unscope_where_column
expected = Post.where("id = 1 or id = 2")
partial = Post.where(id: 1).where.not(id: 2)
assert_equal expected, partial.or(partial.unscope(where: :id).where("id = 2")).to_a
end

def test_or_with_unscope_order
expected = Post.where("id = 1 or id = 2")
assert_equal expected, Post.order("body asc").where("id = 1").unscope(:order).or(Post.where("id = 2")).to_a
end

def test_or_with_incompatible_unscope
error = assert_raises ArgumentError do
Post.order("body asc").where("id = 1").or(Post.order("body asc").where("id = 2").unscope(:order)).to_a
end

assert_equal "Relation passed to #or must be structurally compatible. Incompatible values: [:order]", error.message
end

def test_or_when_grouping
groups = Post.where("id < 10").group("body").select("body, COUNT(*) AS c")
expected = groups.having("COUNT(*) > 1 OR body like 'Such%'").to_a.map { |o| [o.body, o.c] }
Expand Down

0 comments on commit c295296

Please sign in to comment.