Manipulating ActiveRecords using only a few attributes with Ruby on Rails
For caching matters, I'm caching an array of the attributes of the objects I need:
friends = [{:id => 4, :name => "Kevin"}, {:id => 12, :name => "Martin"}, …]
Is it possible to have a list of Users using this array, so that I can use Ruby methods? For ins开发者_开发百科tance, I usually get a list of non-friends with this:
non_friends = User.all - current_user.friends
Here, current_user.friends would be replaced by the cached array, only with the cached attributes:
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>,
…
]
Is it possible? Is it a good approach to caching? (a big list of ActiveRecords doesn't fit into a 1MB Memcache chunk.)
Thank you,
Kevin
edit: The idea behind this is to use a sorted/processed list of 2000 ActiveRecords around which my app heavily uses, but since it doesn't fit into a Memcache chunk, I'm trying to cache the interesting attributes only as an array. Now, how can I use this array like it was an ActiveRecord array?
Well, you can just cache the User IDs and then exclude these IDs in your finder conditions. In your example, assuming you have a friends
array of hashes containing ids and names:
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
精彩评论