Tuesday, 27 August 2013

Strange Rails/ActiveRecord 3.2 HAVING behaviour

Strange Rails/ActiveRecord 3.2 HAVING behaviour

I'm trying to create the following SQL query in Rails 3.2:
SELECT
ordernumber
FROM
orders
WHERE
distributioncenter = 'DC'
GROUP BY
ordernumber
HAVING
COUNT(configrequired)> 0
Which would be in ActiveRecord:
select(:ordernumber)
.where(:distributioncenter => 'DC')
.group(:ordernumber)
.having("COUNT(configrequired) > 0")
(I'm doing this in the Order model, so the FROM is automatic)
However the actual execution of the query completely differs from the above:
SELECT
COUNT(`orders`.`ordernumber`)AS count_ordernumber,
ordernumber,
ordernumber AS ordernumber
FROM
`orders`
WHERE
`orders`.`distributioncenter` = 'DC'
GROUP BY
ordernumber
HAVING
COUNT(configrequired)> 0
Does anyone know how to solve this?
Thank you!

No comments:

Post a Comment