This project is archived and is in readonly mode.

#5829 ✓resolved

ActiveRecord::Relation#empty? fails for grouped relations, as OrderedHash is missing #zero?

Reported by JonnieCache | October 17th, 2010 @ 04:32 PM | in 3.0.6

An activerecord relation with a GROUP BY statement returns an OrderedHash when its calculate method is called, as documented at

When the query returns no results, calling count on it returns an empty OrderedHash. However ActiveRecord::Relation#empty? calls, expecting a Number. It in fact gets the OrderedHash producing

NoMethodError: undefined methodzero?' for #<OrderedHash {}>

Simplest thing would be to change the empty? method to be a bit more smart and check for an empty hash before calling zero?. A wider solution would be to implement zero? for OrderedHash.

My workaround right now is to call count.empty? on the relation object but this is ugly. It also only works if you know that the relation object is definitely representing a query that uses GROUP BY, if you dont know that for sure then you have to put ugly conditional statements in because if count returns an integer, #empty? will obviously not be present. Goodbye model-agnostic partials.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

Referenced by