在GROUP_BY活动记录限制 [英] Active Record LIMIT within GROUP_BY

查看:192
本文介绍了在GROUP_BY活动记录限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情景 我有一个完整的与用户表的职位表。 我希望能够获取所有的职位,他们组的用户,但我想以设定的限额说,10%的用户。

 类岗位<的ActiveRecord :: Base的
    belongs_to的:用户
结束

类用户的LT;的ActiveRecord :: Base的
    的has_many:帖子
结束

#我想这可能工作,但它只是抓住了第10个职位,并将它们分组
Post.find(:所有,:上限=> 10).group_by(安培;:用户)
 

有什么想法?我一定要编写自定义的SQL或者活动记录做到这一点?

解决方案

  Post.group(:USER_ID).limit(10)
 

GROUP_BY 不是查询方法,而是可枚举的方法。

在你的code, Post.find(:所有,:上限=> 10)变成了阵列传递给 GROUP_BY 之前。上述链查询方法一起,只有该方法将它们转换为一个阵列当你需要使用它们。

ActiveRecord的处理整个事情。上述方法转换为

  SELECT`posts`。* FROM`posts` GROUP BY USER_ID LIMIT 10
 

SCENARIO I have a table full of posts with a users table. I want to be able to fetch all the posts and group them by users but I want to set a limit of say 10 per user.

class Post < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
    has_many :posts
end

# I thought this might work but it just grabs the first 10 posts and groups them
Post.find(:all, :limit=>10).group_by(&:user)

Any thoughts? Do I have to write custom SQL for or can Active Record do this?

解决方案

Post.group(:user_id).limit(10)

group_by is not a query method, but rather a method of Enumerable.

In your code, Post.find(:all, :limit => 10) is turned into an Array before being passed to group_by. The method above chains query methods together and only converts them to an Array when you need to use them.

ActiveRecord handles the whole thing. The above method translates to

SELECT `posts`.* FROM `posts` GROUP BY user_id LIMIT 10

这篇关于在GROUP_BY活动记录限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆