2012-03-13 15 views
4

在我的Rails应用程序中,我想用唯一值获取最后10条记录。Mongoid查询!限制和订单的组合

我想:

@users = User.all(:limit => 10, :sort => [:created_at, :desc]).map{|t| t.first_name}.uniq 

但是,

如我所料的限制不起作用..

我想要的 '限价' 影响到最后的查询。

有什么想法?

回答

11
@users = User.desc(:created_at).limit(10).map(&:first_name).uniq 

您应该使用distinct。有可能uniq会使您获得少于10条记录。

@users = User.limit(10).distinct(:first_name).desc(:created_at).map(&:first_name) 
+0

其实问题在于我用uniq获得的数量少于10个。 不幸的是,第二行给出:[]的未定义方法'limit':Array – Lamp 2012-03-13 03:35:58

+0

@vic:方法的排序可能是错误的。我目前无法测试。尝试编辑的版本。 http://mongoid.org/docs/querying/criteria.html#limit – Kyle 2012-03-13 03:46:20

+0

看来@users = User.limit(10).desc(:created_at).distinct(:first_name)几乎可以工作!但忽略排序顺序'desc'..也试过order_by([:created_at,:desc])..但不排序..感谢您的时间! – Lamp 2012-03-13 04:08:58