GROUP_BY 内的 Active Record LIMIT

ale*_*enm 5 sql sqlite activerecord group-by ruby-on-rails

场景 我有一个包含用户表的帖子的表。我希望能够获取所有帖子并按用户对它们进行分组,但我想设置每个用户 10 个的限制。

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)
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我是否必须为此编写自定义 SQL 或者 Active Record 可以这样做吗?

Mat*_*eri 0

就像是?

Post.group(:user_id).limit(10)
Run Code Online (Sandbox Code Playgroud)