That's exactly the kind of thing that I'd argue makes SQL such a great
language, actually -- it's possible to express this kind of query in
just a few lines. (=
It actually looks like Category has_many :stuff, from the sample table
schema given.
I'm still relatively new to Ruby myself, but perhaps you can get away
with something like this?
items = categories.collect { |c| c.stuff[0..2] }.flatten
(.flatten is optional; a nested array might make it easier to print
category headers in a table. I also assume .stuff is sorted via the
:order parameter to has_many.)
I haven't run the above, so YMMV. Note also that this will query for
the entire contents of both tables; you're essentially trading code
written by speed-hungry database geeks for code running in Ruby. If
performance matters, try find_by_sql as well. Either one should
probably be hidden in a class method on Category for consistency's
sake.
Hope this helps,
-Sam
On 7/25/06, Carlos Rodriguez <[EMAIL PROTECTED]> wrote:
Hi,
I was hoping that someone could help me with something that's been
stumping me.
I want to do, as the subject suggests, a top N values per group query
and I was wondering if there was a way to do it "The Ruby Way" as
opposed to writing a complicated find_by_sql or some such.
Here it is:
Table Stuff
id
title
category_id
Table Categories
id
name
Stuff has many categories.
Let's say in the Categories table, I have the values "books, dvds,
music, games."
What I want to do is select the first N from each category. So one
(or two or three..., depending what N is) from books, music, dvd, and
games.
I haven't found very many ways to do this in SQL without writing
complicated queries (see this example: http://support.microsoft.com/
kb/210039/en-us) so I was hoping that Ruby\Rails had some magic
coolness that I didn't know about.
Thanks to anyone in advance that can help me.
If you're going to FOSCON, I'll see you there!
Carlos Rodriguez
[EMAIL PROTECTED]
_______________________________________________
PDXRuby mailing list
[email protected]
IRC: #pdx.rb on irc.freenode.net
http://lists.pdxruby.org/mailman/listinfo/pdxruby
_______________________________________________
PDXRuby mailing list
[email protected]
IRC: #pdx.rb on irc.freenode.net
http://lists.pdxruby.org/mailman/listinfo/pdxruby