Skip to content

Commit

Permalink
Changed the NullRelation so that when count is called with #group it …
Browse files Browse the repository at this point in the history
…will properly return an empty hash instead of zero. Fixes issue #14721

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information
eric-chahin committed Apr 16, 2014
1 parent fe4b0ee commit 93f8525
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Original file line Diff line number Diff line change
@@ -1,3 +1,9 @@
* Fixed a problem where count used with a grouping was not returning a Hash.

Fixes #14721.

*Eric Chahin*

* `sanitize_sql_like` helper method to escape a string for safe use in a SQL * `sanitize_sql_like` helper method to escape a string for safe use in a SQL
LIKE statement. LIKE statement.


Expand Down
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/null_relation.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def to_sql
end end


def count(*) def count(*)
0 calculate :count, nil
end end


def sum(*) def sum(*)
Expand All @@ -54,7 +54,7 @@ def calculate(operation, _column_name, _options = {})
# TODO: Remove _options argument as soon we remove support to # TODO: Remove _options argument as soon we remove support to
# activerecord-deprecated_finders. # activerecord-deprecated_finders.
if operation == :count if operation == :count
0 group_values.any? ? Hash.new : 0
else else
nil nil
end end
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/relations_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
require 'models/engine' require 'models/engine'
require 'models/tyre' require 'models/tyre'
require 'models/minivan' require 'models/minivan'
require 'models/aircraft'




class RelationTest < ActiveRecord::TestCase class RelationTest < ActiveRecord::TestCase
Expand Down Expand Up @@ -365,6 +366,16 @@ def test_null_relation_where_values_hash
assert_equal({ 'salary' => 100_000 }, Developer.none.where(salary: 100_000).where_values_hash) assert_equal({ 'salary' => 100_000 }, Developer.none.where(salary: 100_000).where_values_hash)
end end



def test_null_relation_count
ac = Aircraft.new
assert_equal Hash.new, ac.engines.group(:id).count
assert_equal 0, ac.engines.count
ac.save
assert_equal Hash.new, ac.engines.group(:id).count
assert_equal 0, ac.engines.count
end

def test_joins_with_nil_argument def test_joins_with_nil_argument
assert_nothing_raised { DependentFirm.joins(nil).first } assert_nothing_raised { DependentFirm.joins(nil).first }
end end
Expand Down

0 comments on commit 93f8525

Please sign in to comment.