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

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

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

谢谢...

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

编辑:

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=> 选项。

有帮助吗?

解决方案

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

其他提示

尝试 Rails uniq_by。它也可以使用关联并返回数组。

@document = Model.uniq_by(&:field)

更多的 细节

我想你就可以做到这一点使用的find_by_sql和GROUP BY:

Games.find_by_sql("SELECT * FROM games GROUP BY user_id")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top