Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find() all records unique in certain fields?

I have a list of 'request' objects, each of which has fairly normal activerecord qualities. The requests table is related to the games table with a join table, 'games_requests,' so that a request has a request.games array.

The question is, is there a way to do a find for the last n unique requests, where uniqueness is defined by the games column and a couple others, but specifically ignores other colums (like the name of the requesting user?)

I saw a syntax like 'find (:all, :limit=>5, :include=>[:games,:stage])' but that was returning duplicates.

Thanks...

EDIT: Thanks to chaos for a great response. You got me really close, but I still need the returns to be valid request objects: the first 5 records that are distinct in the requested rows. I could just use the find as you constructed it and then do a second find for the first row in the table that matches each of the sets returned by the first find.

EDIT:

Games.find(
    :all, :limit => 5,
    :include => [:games, :requests],
    :group => 'games, whatever, whatever_else'
)

...gives an SQL error:

Mysql::Error: Unknown column 'games' in 'group statement': SELECT * FROM `games`  GROUP BY games

I made a few changes for what I assumed to be correct for my project; getting a list of requests instead of games, etc:

Request.find(
    :all, :order=>"id DESC", :limit=>5,
    :include=>[:games],   #including requests here generates an sql error
    :group=>'games, etc'  #mysql error:  games isn't an attribute of requests
    :conditions=>'etc'
)

I'm thinking I'm going to have to use the :join=> option here.

like image 211
Sniggerfardimungus Avatar asked Mar 16 '09 16:03

Sniggerfardimungus


2 Answers

Games.find(
    :all, :limit => 5,
    :include => [:games, :requests],
    :group => 'games, whatever, whatever_else'
)
like image 160
chaos Avatar answered Nov 06 '22 20:11

chaos


Try Rails uniq_by.It also works with association and returns array.

@document = Model.uniq_by(&:field)

More Detail

like image 29
imsinu9 Avatar answered Nov 06 '22 21:11

imsinu9