Active LIMIT record inside GROUP_BY

SCENARIO I have a table full of messages with a user table. I want to be able to receive all messages and group them by users, but I want to set a limit, for example, 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? Should I write my own SQL for Active Active Record or do this?

+4
source share
2 answers

Sort of?

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

group_by is not a request method, but an Enumerable method.

In your code, Post.find(:all, :limit => 10) turns into Array before passing group_by . The method above combines query methods and converts them only to Array when you need to use them.

ActiveRecord handles all this. The above method is converted to

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

Source: https://habr.com/ru/post/1395854/


All Articles