2010-10-22 27 views
0

緩存的問題,我緩存我需要的對象的屬性的數組:操縱僅使用幾個屬性與紅寶石ActiveRecords on Rails的

friends = [{:id => 4, :name => "Kevin"}, {:id => 12, :name => "Martin"}, …] 

是否有可能在使用用戶列表這個數組,讓我可以使用Ruby方法?舉例來說,我通常得到的非好友列表與此:

non_friends = User.all - current_user.friends 

這裏,current_user.friends將由緩存陣列來代替,只能用緩存的屬性:

friends = [ 
    #<User id: 4, name: "Kevin", created_at: nil, updated_at: nil, email: nil>, 
    #<User id: 12, name: "Martin", created_at: nil, updated_at: nil, email: nil>, 
    … 
] 

是它可能?這是緩存的好方法嗎? (ActiveRecords的大名單不適合1MB的內存緩存塊。)

謝謝

凱文

編輯:這背後的想法是使用的分類/加工名單2000 ActiveRecords我的應用程序大量使用,但由於它不適合Memcache塊,我試圖緩存有趣的屬性只能作爲一個數組。現在,我怎樣才能像這是一個ActiveRecord數組使用這個數組?

+0

你是什麼意思與「這樣我就可以使用Ruby方法」?我不確定你想要做什麼?也許你應該使用另一種行爲而不是緩存10000個朋友? – Lichtamberg 2010-10-22 13:54:30

+0

Ruby數組方法,比如「&」或「 - 」是非常有用的,但我無法比較像User.all這樣的ActiveRecord數組和像[[:ID => 1,:name => 「Kevin」},...]' – 2010-10-22 14:12:06

+0

User.all.to_a - User.find(:all,:active => true).to_a的作品? :D而我不明白它.. Rails的AR集合有大部分的數組方法? – Lichtamberg 2010-10-22 14:29:03

回答

1

那麼,您可以緩存用戶ID,然後在您的查找器條件中排除這些ID。在您的例子,假設你有一個friends陣列包含ID和名稱哈希:

friend_ids = friends.map{ |f| f[:id] } 
if friend_ids.empty? 
    non_friends = User.all 
else 
    non_friends = User.all(:conditions => ['id NOT IN (?)', current_user.friend_ids]) 
end 
+0

我仍然需要查詢數據庫,但是對於比不使用緩存的用戶更少的用戶來說是正確的。我會試試這個。謝謝 :-) – 2010-10-22 16:19:47