Active Record LIMIT within GROUP_BY

二次信任 提交于 2019-12-22 08:46:42

问题


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?


回答1:


Something like?

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



回答2:


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


来源:https://stackoverflow.com/questions/9235903/active-record-limit-within-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!