locoboy
locoboy

Reputation: 38940

limit collect in ruby

I currently have the following:

users = User.all   
comments = users.collect(&:comments)

However, if there are thousands of comments, i'd like to only collect 10 from each user to limit the number of database queries that are made. Is there a way to do this?

Upvotes: 1

Views: 311

Answers (4)

Michaël Witrant
Michaël Witrant

Reputation: 7714

users = User.all
comments = users.collect { |user| user.comments.limit(10) }

Or with another association in you model :

has_many :first_comments, :class_name => "Comment", :limit => 10

Then this will result in only two database queries:

users = User.includes(:first_comments)
comments = users.collect(&:first_comments)

Upvotes: 1

evfwcqcg
evfwcqcg

Reputation: 16345

users = User.all
comments = Comment.order("DESC created_at").limit(10).all

Or, if you only need users for these 10 recent comments, you can try

comments = Comment.includes(:users).order("DESC created_at").limit(10).all
users = comments.map(&:user)

Upvotes: 0

Pritesh Jain
Pritesh Jain

Reputation: 9146

Try this

comments = Comment.where(:user_id=>users).limit(10)

or

comments = Comment.all(:conditions => {:user_id=>users}, :limit => 10)

You can use any one that suits you

Upvotes: 0

TomDunning
TomDunning

Reputation: 4877

The easiest in terms of query looks a little convoluted:

Comment.where(["user_id IN (?)", users.collect(&id) ]).limit(10)

I presume your sort order is set by a default scope somewhere.

Rails 2:

Comment.all(:conditions => ["user_id IN (?)", users.collect(&id) ], :limit => 10)

Upvotes: 0

Related Questions