2013-12-11 132 views
0

我有以下的has_many和belongs_to的关系:导轨 - 检索重复的记录

class Trophy < ActiveRecord::Base 
    has_many :awards 
end 

class Award < ActiveRecord::Base 
    belongs_to :trophy 
end 

颁奖模型具有user_id场和trophy_id场。

对于奖杯的一个例子,我想返回5个最近的,但不同的用户奖项。

我可以这样做:

def recent_awards 
    trophy_awards = awards.recent.includes(:user) 
    trophy_awards.uniq! {|a| a.user_id} 
    trophy_awards[0...4] 
end 

然而,这不是有效的,因为我处理了很多纪录。

目前,我这样做:

def recent_awards 
    trophy_awards = awards.limit(50).recent.includes(:user) 
    trophy_awards.uniq! {|a| a.user_id} 
    trophy_awards[0...4] 
end 

问题是,它不会给我5个不同的用户奖励,如果最后48个奖项是相同的用户。

返回5个最近的,但不同的用户奖励的最佳方式是什么?

+0

哦,这是一个真棒SQL的问题,我将不得不重温我的大脑的一部分,我没有用在一段时间... – RustyToms

+0

http://stackoverflow.com/questions/5125209/how-to-fetch-distinct-values-with-arel-relational-algebra-and-has-many-through –

回答

0

试试这个:

Award.find_by_sql("SELECT * 
    FROM awards a1 INNER JOIN (
    SELECT MAX(created_at) AS recent 
    FROM awards 
    GROUP BY user_id) a2 
    ON (a1.created_at = a2.recent) 
    ORDER BY a1.created_at DESC 
    LIMIT 5;") 
+0

这是给我postgres语法错误......应该说我使用postgres – keruilin

+0

@keruilin,我编辑了答案。为我的项目修改过的一个版本适用于我,请检查它并让我知道是否需要进行其他更改。 – RustyToms

+0

嗯,它不应该抛出一个错误,但实际上我不确定它是否会让你最近的:( – RustyToms