2012-08-12 121 views
1

收集目前,我有以下幾點:極限紅寶石

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

但是,如果有數千條評論,我想只收集10從每個用戶來限制由數據庫查詢的次數。有沒有辦法做到這一點?

回答

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

或者在你的模型另一個關聯:

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

,那麼這將導致只有兩個數據庫查詢:

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

如果你使用'flat_map','comments'將會是一個普通的數組(我猜這就是OP想要的)。 – tokland 2012-08-12 08:46:12

0

試試這個

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

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

您可以使用適合您

+0

用戶是用戶是'limit'行不通的數組。此外,我不想限制用戶數量,我想限制評論數量(所有最新的評論) – locoboy 2012-08-12 07:18:48

+0

這將是前10位用戶的評論,而不是10評論。 .limit(10)需要結束。 – TomDunning 2012-08-12 07:19:34

+0

@locoboy,查看我的更新回答 – PriteshJ 2012-08-12 07:52:18

0

最簡單的查詢方面的任何一個看起來有點令人費解:

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

我認爲你的排序r由某個默認範圍設置。

梁2:

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

我剛剛意識到這不是你要求的。你要求10 /用戶。然而,這不是一個限制結果的好方法,因爲隨着用戶的增長,您的輸出將會增加(當您擁有5k用戶時會發生什麼)。最好限制最終名單。 – TomDunning 2012-08-12 07:43:24

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

或者,如果你只需要用戶對於這10個最近的評論,你可以嘗試

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