From 12afdba8b9083f52d6b78ec9f16cf17e14f5222e Mon Sep 17 00:00:00 2001 From: Gannon McGibbon Date: Wed, 13 Nov 2019 17:35:28 -0500 Subject: [PATCH] Fix unscoped grouped where --- activerecord/CHANGELOG.md | 4 ++++ activerecord/lib/arel.rb | 16 +++++++++++++--- activerecord/test/cases/relations_test.rb | 9 +++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 66b4a47cad..d46a880e42 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* Allow attributes to be fetched from Arel node groupings. + + *Jeff Emminger*, *Gannon McGibbon* + * Calling methods like `establish_connection` with a `Hash` which is invalid (eg: no `adapter`) will now raise an error the same way as connections defined in `config/database.yml`. *John Crepezzi* diff --git a/activerecord/lib/arel.rb b/activerecord/lib/arel.rb index deb3e26e0e..75333d49f6 100644 --- a/activerecord/lib/arel.rb +++ b/activerecord/lib/arel.rb @@ -46,10 +46,20 @@ def self.arel_node?(value) # :nodoc: value.is_a?(Arel::Node) || value.is_a?(Arel::Attribute) || value.is_a?(Arel::Nodes::SqlLiteral) end - def self.fetch_attribute(value) # :nodoc: + def self.fetch_attribute(value, &block) # :nodoc: case value - when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual - yield value.left.is_a?(Arel::Attributes::Attribute) ? value.left : value.right + when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, + Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, + Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual + if value.left.is_a?(Arel::Attributes::Attribute) + yield value.left + else + yield value.right + end + when Arel::Nodes::Or + fetch_attribute(value.left, &block) && fetch_attribute(value.right, &block) + when Arel::Nodes::Grouping + fetch_attribute(value.expr, &block) end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 6af8b458f5..687e98fe0d 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -2050,6 +2050,15 @@ def test_unscope_specific_where_value assert_equal 1, posts.unscope(where: :body).count end + def test_unscope_grouped_where + posts = Post.where( + title: ["Welcome to the weblog", "So I was thinking", nil] + ) + + assert_equal 2, posts.count + assert_equal Post.count, posts.unscope(where: :title).count + end + def test_locked_should_not_build_arel posts = Post.locked assert_predicate posts, :locked? -- GitLab