acts_as_most_popular
Wolfram ArnoldRubyFocus
User Activity Tracking
Join between:
Viewable entity (user profile, image, post, video ...)
Activity tracking(viewings, comments, ratings ...)
Item.find(:all,
:select => 'items.*,
COUNT(*) AS viewing_count',
:joins => :viewings,
:limit => limit,
:group => 'viewings.item_id',
:order => 'viewing_count DESC')
acts_as_most_popularacts_as_most_popular
acts_as_most_popular
I want:Most popular list from cache
Cache populared from database once
List automatically kept sorted & indexed in cache
I need:
A caching framework
Ideally something common, transparent & flexible
Cache MoneyCache Money
Cache Money
Transparent
find vs. get_cache
Sequence
AR Cache SQL
find → get → select
update → set → update
create → add → insert
destroy → delete/expire → delete
Maintains indices automatically!
Cache Money
Instance methods on models:
get
set
repository
Automatic key handling
User.set(“new_key”)
→ Key: “User:1/new_key”
SolutionSolution
acts_as_most_popular
Additional index, sorted by activity count
primed on first access
maintained via after_add, after_remove callbacks
Definition
class Item < ActiveRecord::Base
has_many :viewings
acts_as_most_popular \
:activity_association => :viewings,
:limit => 5,
:db_finder_args =>
{ :select => 'item_id,
COUNT(*) AS activity_count',
:group => 'item_id' }
end
Usage
class StatsController < Application
def most_popular
@items = Item.most_popular
end
end
References
Cache Money
http://magicscalingsprinkles.wordpress.com/2008/12/11/introducing-cache-money/
http://github.com/nkallen/cache-money/tree/master
Images
http://www.flickr.com/photos/flirtykitty/142229288/
http://www.flickr.com/photos/jojakeman/2434236126/