ActiveRecord calculation fail when having contains conditions based on select values #1969

merged 1 commit into from Jul 27, 2011

5 participants


Current implementation of ActiveRecord#calculate is that it drops provided select values. This ruins query when calling calculate on a relation with having conditions based on select.


class User < ActiveRecord::Base
  has_many :operations

class Operation < ActiveRecord::Base
  belongs_to :user

relation = User.joins(:operations).select("sum(operations.amount) AS deposit").group("").having("deposit > 100")
relation.count # raises sql error "no such column 'deposit'"

Provided patch fixes the error by keeping select values untouched if there is having clause in query.

Bug occurs in master, 3-1-stable and 3-0-stable


I am also want to this bug to be fixed.

Ruby on Rails member
@jonleighton jonleighton commented on an outdated diff Jul 27, 2011
@@ -170,6 +170,22 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 60, c[2]
+ def test_should_group_by_summed_field_having_condition_from_select_in_relation
+ c ="MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("min_credit_limit > 50").sum(:credit_limit)
+ assert_nil c[1]
+ assert_equal 60, c[2]
+ assert_equal 53, c[9]
+ end
+ def test_should_group_by_summed_field_having_condition_from_select_in_options
jonleighton Jul 27, 2011 Ruby on Rails member

Can you remove this one please? it's not really necessary as the hash-options form only builds up a Relation object anyway. Then I am happy to merge.

@jonleighton jonleighton merged commit 091e767 into rails:master Jul 27, 2011
Ruby on Rails member

@jonleighton should we apply this in 3-1-stable?

Ruby on Rails member

@spastorino unsure. maybe we should target for 3.1.1 to avoid potentially destabilising the RCs?

Ruby on Rails member

@jonleighton sure, so should we add an issue to remind us this?

Ruby on Rails member

Done: #2304

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment