2012-12-13 19 views
0

我經常遇到這種情況。將ActiveRecord從已經緩存的內容獲取到查詢

post_comments = post.comments 
#grabs maybe 3 records out of thousands in the table 
do_something_with post_comments 

#...later in the same request... 

subset_of_comments = post_comments.where(:awesome=>true) 
#hits the database again :-(
do_something_else subset_of_comments 

我認識到數據庫在查找記錄非常好,但我不明白怎麼回事回滿了桌子和期待通過成千上萬的記錄是不是搜索小的記錄集連接到這更好已經爲我需要的1或2個緩存了。

如果我想提高此過程的效率,該怎麼辦?

回答

1

是的。第一次加載AR:Relation之後,所有記錄都被緩存。但是如果您通過另一個請求.where()或其他請求,它會再次提取查詢。如果您想要在緩存記錄中進行搜索,請不要發送.where,只需使用數組方法

# second 'request': 
subset_of_comments = post_comments.map {|comment| comment if comment.awesome == true}.compact 

Array方法: .find - 一個第一個匹配的記錄。 .map.collect - 用於收藏

您的評論對象必須具有「真棒」公衆閱讀器。

+0

不正確的!這不會返回post_comments的子集。只是一個布爾值數組。 – atmaish

+0

你是對的,我只是改變了發現地圖,並忘記糾正塊 –

+0

謝謝,這是相當明顯,實際上。出於某種原因,我對使用ruby枚舉函數有一個心理障礙。我想我只是覺得這很酷,如果ActiveRecord記得我之前是否在其他地方完成過濾。 – pseudopeach