出於某種原因,它似乎像.each
塊迭代只有一次,當我寫可以說,3個或4個評論,@total_comments
只顯示1,而不是3或4紅寶石。每塊不加起來的所有對象
的關係是:
- 用戶有很多帖子
- 後有很多評論
任何人可以幫助嗎?
控制器
@total_comments = 0
@posts = current_user.posts
@posts.each do |post|
@comments = post.comments
@new_comments = @comments.count [email protected]("created_at < ?",1.day.ago).count
@total_comments += @new_comments
end
視圖
<%= @total_comments %>
肯定比它需要更復雜? – 2011-11-08 19:33:35
只需在SQL中使用COUNT(*),JOIN和GROUP BY語句,或者使用等效的Rails助手,就可以獲得更簡單快捷的版本。 – robbrit
這裏的問題是,如上所述,你可以做到這一點更簡單。這是n + 1的經典例子(如果有10個帖子,這將導致對您的數據庫有11個查詢)。嘗試使用上述建議進行清理。另外,您並不需要製作@評論,@ old_comments和@ new_comments實例變量。 – mynameiscoffey