问题
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