And you can actually represent this in AR friendly syntax; no console
in front of me but its something like

Player.find(:select => "players.id", :joins => :trophies, :group =>
'players.id', :having => 'count(players.id) > 5')

Downside of this is that the returned objects in this case would only
have ID attribute; you can add more to the select, but you need to add
them to the :group as well.  Would be nice if there was a better way
to do this; SQL requires them in both the select and group_by, but
it'd be nice if rails would auto do that for the table I'm doing the
find on by default.

\Peter

On Feb 14, 6:31 am, Frederick Cheung <[email protected]>
wrote:
> On Feb 14, 6:54 am, Frank Kim <[email protected]> wrote:
>
> > I have a model, let's call it Player.
>
> > It has many Trophies.
>
> > How do I do a simple query in Rails in my controller that will return
> > let's say all Players that have more than 5 tropies?
>
> > Sorry for the dumb question but I can't figure it out. :-)
>
> If for some reason you don't want to use a counter cache then you can
> write it as
>
> SELECT players.*, count(*) as trophy_count from players
> inner join trophies on trophies.player_id = players.id
> group by players.id having trophy_count > 5
>
> But using a counter_cache and an index on that column would be way
> faster.
>
> Fred

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to