2009-07-24 71 views
13

預先加載是好的與包括屬性Rails急於加載計數?

Post.find(:all, :include => :author) 

我想知道,如果可以的話也渴望負荷數,就像如果我想獲得的每個帖子的評論的數量,而不加載所有評論自己呢?

也許像

Post.find(:all, :include => [:author, "count(comments)") 

我想我可以用一個count_cache列。但是如果可能的話,在一個包含內容中進行所有操作將會非常美麗。

如果有人能夠展示如何獲得計數,但也提出了一些條件,比如只有已批准的職位數,才能獲得額外的獎勵積分。

+0

這是後來擴展在這個問題:http://stackoverflow.com/questions/4908878/how-do-i-get-rails-to-eager-load-counts 這是強烈相關:http:///stackoverflow.com/questions/2870521/how-will-activerelation-affect-rails-includes-s-capabilities(這是我的發現。) – 2011-02-27 19:19:26

回答

-6

在MySQL中至少有兩個獨立的調用會更快,因爲你避免了加入。我知道這並不能回答你的問題,但它好像你正在試圖獲得更好的速度和做

Post.find ... 

然後

post.comments.count 

是更快,更高效的內存(數據庫)比如果您在一個查詢中檢索到這兩個字符

24

因爲我用.Count之間

+2

我不認爲這是他正在尋找。這將加載評論關聯中的所有條目,然後對它們進行計數。他希望在不加載對象的情況下使用SQL來引發計數。 (或者至少這是我的理解)。 – Mike 2009-11-24 20:08:36

+0

你是對的Mike。 – 2009-12-03 23:30:08

+1

這是我正在尋找的解決方案。在我想要迭代集合並顯示註釋數量的帖子的索引頁上,這可以避免在每個週期中觸發計數請求(假設註釋已經與帖子一起加載)。感謝:-) – Renra 2014-06-29 08:40:46

2

試試這個,他們應該已經被加載使用

post.comments.length 

我有同樣的問題:

Comment.count(:group => :post) 

要根據條件篩選:

Comment.count(:group => :post, :conditions => {:approved => true }) 

這些將以帖子作爲關鍵字以及作爲值的註釋數量返回散列值。

3

建立了avaynshtok的答案,下面的技術應該只做2個數據庫調用。

# ./app/controllers/posts_controller.rb 

def index 
    # First load the posts 
    @posts = Post.all 

    # Then you can load a hash of author counts grouped by post_id 
    # Rails 3 version: 
    @comment_counts = Comment.count(:group => :post_id) 
    # Rails 4 version: 
    # @comment_counts = Comment.group(:post_id).count 
end 

然後在您的視圖

<!-- ./app/views/posts/index.html.erb --> 

<% @posts.each do |post| %> 
    <!-- reference the count by the post.id --> 
    post_count: <%= @comment_counts[post.id] %> 
<% end %> 
0

我只是碰到了這個挑戰,並解決了它這種方式:

def trainee_counts 
    @trainee_counts ||= Hash[Trainee.group(:klass_id).count] 
end 

    # where the count is needed 
    trainee_counts[klass_id].to_i 

一個調用數據庫,並不會加載學員。