Rails:如何找到()某些字段中唯一的记录?

Sni*_*gus 10 activerecord ruby-on-rails unique distinct find

我有一个'request'对象列表,每个对象都有相当正常的activerecord特性.requests表与带有连接表'games_requests'的游戏表相关,因此请求具有request.games数组.

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

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

谢谢...

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

编辑:

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

...给出了一个SQL错误:

Mysql::Error: Unknown column 'games' in 'group statement': SELECT * FROM `games`  GROUP BY games
Run Code Online (Sandbox Code Playgroud)

因为我认为对我的项目来说是正确的,我做了一些改变; 获取请求列表而不是游戏等:

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'
)
Run Code Online (Sandbox Code Playgroud)

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

cha*_*aos 9

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


ims*_*nu9 6

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

@document = Model.uniq_by(&:field)

更多细节

  • 认为`uniq_by`被折旧并被`uniq`取代. (2认同)