【发布时间】:2013-12-11 04:34:11
【问题描述】:
我有以下has_many和belongs_to关系:
class Trophy < ActiveRecord::Base
has_many :awards
end
class Award < ActiveRecord::Base
belongs_to :trophy
end
Award 模型有一个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
问题是,如果最后 48 个奖项颁发给同一个用户,它不会给我 5 个不同的用户奖项。
返回 5 个最新但不同的用户奖项的最佳方式是什么?
【问题讨论】:
-
哦,伙计,这是一个很棒的 SQL 问题,我将不得不清理一下我有一段时间没用过的大脑部分......
标签: sql ruby-on-rails ruby-on-rails-3 postgresql distinct