Ludovic
Ludovic

Reputation: 2002

Count with ActiveRecordObject.select

I would like to do something like this

User.select("users.id, count(whatever) as test")

But rails return only the User.id without the count. I can't use something like

User.count(whatever)

Because I use this select in a very complex SQL query. Is it possible to get the count value with select helper ?

Upvotes: 0

Views: 35

Answers (1)

vee
vee

Reputation: 38645

Are you sure the following query returns User.id? Doesn't it throw an error saying "column is invalid in the select list because it is not contained in either an aggregate function or the group by clause":

User.select("users.id, count(whatever) as test")

Because you are using count you should also use group method as following:

User.select("users.id, count(whatever) as test").group("users.id, whatever")

Then your resultant array will contain users.id and count(whatever).

Upvotes: 1

Related Questions