10

我有一个“请求”对象的列表,每个对象都具有相当正常的活动记录质量。requests 表通过连接表“games_requests”与游戏表相关联,因此请求具有 request.games 数组。

问题是,有没有办法找到最后 n 个唯一请求,其中唯一性由游戏列和其他几个列定义,但特别忽略其他列(如请求用户的名称?)

我看到了类似 'find (:all, :limit=>5, :include=>[:games,:stage])' 的语法,但它返回了重复项。

谢谢...

编辑:感谢混乱的伟大回应。你让我非常接近,但我仍然需要返回是有效的请求对象:在请求的行中不同的前 5 条记录。我可以在构建时使用 find,然后对表中与第一个 find 返回的每个集合匹配的第一行进行第二个 find。

编辑:

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

...给出一个 SQL 错误:

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

我对我认为对我的项目正确的内容进行了一些更改;获取请求列表而不是游戏等:

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'
)

我想我将不得不在这里使用 :join=> 选项。

4

3 回答 3

9
Games.find(
    :all, :limit => 5,
    :include => [:games, :requests],
    :group => 'games, whatever, whatever_else'
)
于 2009-03-16T17:00:28.823 回答
6

试试 Rails uniq_by。它也适用于关联并返回数组。

@document = Model.uniq_by(&:field)

更多细节

于 2013-10-10T22:59:14.160 回答
0

我认为您可以使用 find_by_sql 和 GROUP BY 来做到这一点:

Games.find_by_sql("SELECT * FROM games GROUP BY user_id")
于 2009-03-16T16:49:20.130 回答