views:

4502

answers:

2

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.

A: 

I think you'll be able to do this using find_by_sql and GROUP BY:

Games.find_by_sql("SELECT * FROM games GROUP BY user_id")
Mr. Matt
+3  A: 
Games.find(
    :all, :limit => 5,
    :include => [:games, :requests],
    :group => 'games, whatever, whatever_else'
)
chaos
This returns the games, whatever, and whatever_else columns. Is there a way to return complete request objects, ejecting only those that fail the uniqueness in these columns?
Yeah. Edited per.
chaos
Hrm. Has an issue with 'games' being a virtual attribute through a join table. (see edited question)
It's really hard to write something that will work without knowing your actual table structure. Possibly :group => 'games' should be :group => 'game_id' because that's the name of the column in requests?
chaos
Oh, right, you have a many-to-many. Yeah, you'll need a :join spec to bring in your games_requests table, then group on the game_id column from that.
chaos