Forum: Ruby on Rails find :all using :group

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ayeye B. (Guest)
on 2009-03-23 16:21
hello,

I need to group Users depending on their operating systems field "os",
so I tried

User.find(:all, :group => :os)

however, the result is an array having only one user for each os group.
I'd like to have ALL the users grouped  by :os though

One solution is to write

User.find(:all).group_by{|u| u.os}

However, I wonder if it could be done within the "find" method ?

thanks
Jeff E. (Guest)
on 2009-03-23 20:25
(Received via mailing list)
This sounds right to me... find the SQL it generated in your .log and
execute it in a mysql console... is the output the same?


On Mar 23, 10:21 am, Ayeye B. <removed_email_address@domain.invalid>
Frederick C. (Guest)
on 2009-03-23 20:39
(Received via mailing list)
On Mar 23, 2:21 pm, Ayeye B. <removed_email_address@domain.invalid>
wrote:

> User.find(:all, :group => :os)
>
> however, the result is an array having only one user for each os group.
> I'd like to have ALL the users grouped  by :os though
>
> One solution is to write
>
> User.find(:all).group_by{|u| u.os}
>
> However, I wonder if it could be done within the "find" method ?

Not really. By definition if you group using the database then you
only get back one row for each value of the grouped column  - that's
just what group does in database and you want something else.

Fred
Eric (Guest)
on 2009-03-23 21:01
(Received via mailing list)
On Mar 23, 11:38 am, Frederick C. <removed_email_address@domain.invalid>
wrote:
> > User.find(:all).group_by{|u| u.os}
>
> > However, I wonder if it could be done within the "find" method ?
>
> Not really. By definition if you group using the database then you
> only get back one row for each value of the grouped column  - that's
> just what group does in database and you want something else.

...such as :order => 'os ASC'
Party Drone (Guest)
on 2009-03-23 21:22
(Received via mailing list)
User.find(:all, :order => 'os')

:order sorts ascending by default.  You can define the sort order
explicitly with ASC or DESC (i.e., 'os ASC' or 'os DESC').


On Mar 23, 8:21 am, Ayeye B. <removed_email_address@domain.invalid>
Ayeye B. (Guest)
on 2009-03-24 00:26
>> However, I wonder if it could be done within the "find" method ?
>
> Not really. By definition if you group using the database then you
> only get back one row for each value of the grouped column  - that's
> just what group does in database and you want something else.
>
> Fred

I see, thanks for that Fred.

Thanks all for the replies
a.
This topic is locked and can not be replied to.