我有以下的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个最近的,但不同的用户奖励的最佳方式是什么?
哦,这是一个真棒SQL的问题,我将不得不重温我的大脑的一部分,我没有用在一段时间... – RustyToms
http://stackoverflow.com/questions/5125209/how-to-fetch-distinct-values-with-arel-relational-algebra-and-has-many-through –