On 18 January 2011 18:06, James Byrne <li...@ruby-forum.com> wrote:
> Tim Shaffer wrote in post #975786:
>> Here is an example of code that would fit your needs:
>>
>> records = []
>> Category.all.each do |category|
>>   records << category.clients.first
>> end
>
> Yes, that is what I ended up doing, more or less. What I did was this:
>
>> cset = []
>> Client.select("DISTINCT(client_category)").each do |c|
>>  cset << Client.find_by_client_category(c.client_category)
>> end
>

To solve it in SQL you would (probably) need sub-queries or unions to
join distinct rows for each type of category... all very messy (as has
been hinted).

Comparing your solution to Tim's suggestion, I infer that you don't
have "client_category" as an association? (ie: client belongs_to
:category).
You could use the "group_by" method for collections, and select the
first off each group - that saves you doing a query per client, at the
cost of doing one large query and a load of Ruby iteration.

  Client.all.group_by(&:client_category).map(&:first)

... it's also easily chainable to write on one line (but you could
compress your own solution to one line with .inject instead of .select
- so it's not exactly much different my way, but possibly a little
more legible?)

At the end of the day, you're in the realms of doing some fudging to
get the data out you're after (as you've discovered), as you're not
doing something that's a natural fit for the DB or ORM. Sorry if
that's not massively helpful... just letting you know we feel your
pain.

-- 
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 rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to