2017-03-01 73 views
2

我在我的車型之一漂亮的DB-密集類方法:緩存類方法的結果集?

class Page < ApplicationRecord 
    def self.collection_tree 
    pages = [] 
    walk_tree do |page, level| 
     pages << page 
    end 
    pages 
    end 
end 

我想緩存結果所以只有在首次調用方法調用的數據庫查詢。

我想它是這樣的:

def self.collection_tree 
    return @collection_tree if @collection_tree 

    @collection_tree = [] 
    walk_tree do |page, level| 
    @collection_tree << page 
    end 
    @collection_tree 
end 

,但是這導致的規格隨機失敗 - 看來,這不是他們的方式如我所料規格之間重置。

是否有另一種方法來緩存這樣的東西?

回答

1

使用直接與fetch method

def self.collection_tree 
    Rails.cache.fetch('collection_tree') do  
    collection_tree = [] 
    walk_tree do |page, level| 
     collection_tree << page 
    end 
    collection_tree 
    end 
end 
緩存