Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Multiple having calls on an ActiveRecord::Relation causes "wrong number of arguments (2 for 1)" error

#6661

Let's use any model (i.e. Model) and execute in console:

Model.select('id').group('id').having('2 > 1')

and we'll get the sql query similar to:

SELECT id FROM "models" GROUP BY id HAVING 2 > 1

That is okay.

Then execute in console:

Model.select('id').group('id').having('2 > 1').having('3 > 1')

and we'll get the following error:

ArgumentError: wrong number of arguments (2 for 1)

from /home/cryo/.rvm/gems/ruby-1.8.7-p334@appstore/gems/activerecord-3.0.5/lib/active_record/relation/query_methods.rb:181:in `having'
from /home/cryo/.rvm/gems/ruby-1.8.7-p334@appstore/gems/activerecord-3.0.5/lib/active_record/relation/query_methods.rb:181:in `build_arel'
from /home/cryo/.rvm/gems/ruby-1.8.7-p334@appstore/gems/activerecord-3.0.5/lib/active_record/relation/query_methods.rb:150:in `arel'
from /home/cryo/.rvm/gems/ruby-1.8.7-p334@appstore/gems/activerecord-3.0.5/lib/active_record/relation.rb:64:in `to_a'
from /home/cryo/.rvm/gems/ruby-1.8.7-p334@appstore/gems/activerecord-3.0.5/lib/active_record/relation.rb:356:in `inspect'

Why does it happen?

Calling having on ActiveRecord::Relation collects having clauses into an array
relation.having_values += build_where(*args) unless args.blank?

The the following code in active_record/relation/query_methods.rb:181:in `build_arel' passes as many arguments to arel.having as the quantity of collection having clauses in relation. But in seems the having method of arel accepts only 1 argument expr.

arel = arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?

Reported by Artem Ignatyev · April 1st, 2011 @ 07:59 AM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Lewis Marshall
    Lewis Marshall

    I've spotted the problem with this.

    Looking at the latest rails/arel source, Arel::SelectManager#having takes multiple arguments but Arel::Table#having only takes a single argument. Splatting the Arel::Table#having argument seems to solve the problem you have mentioned.

    I'm new to bugfixing so not sure how to sufficiently verify this doesnt break anything else!

    April 2nd, 2011 @ 12:59 AM