Tracking Views in Rails

May 22nd, 2007

ActsAsViewable is plugin that allows you to track page and asset views in your Rails application. For example, you can use it to track how many times a page is visited or how many times a particular image is viewed.

Trac: http://trac.intridea.com/trac/public/wiki/ActsAsViewable

Subversion repository: http://svn.intridea.com/svn/public/acts_as_viewable

Installation:
script/plugin install http://svn.intridea.com/svn/public/acts_as_viewable

OR

cd vendor/plugins
svn co http://svn.intridea.com/svn/public/acts_as_viewable

Create the tables where views will be tracked:

class CreateViewings < ActiveRecord::Migration
  def self.up
    create_table :viewings do |t|
      t.column :viewable_type,  :string
      t.column :viewable_id,    :integer
      t.column :views,          :integer,   :default => 0
      t.column :created_at,     :datetime, :null => false
      t.column :updated_at,     :datetime
    end
  end

  def self.down
    drop_table :viewings
  end
end
Set the objects you want to track views for:
class SomeAsset < ActiveRecord::Base
  acts_as_viewable
end

Now you can increment views for these objects wherever you need to. For example in the show action of our SomeAssetController:

class SomeAssetController < ApplicationController
  def show
    @some_asset = SomeAsset.find(params[:id])
    @some_asset.increment_views
  end
end

To get the number of views:

@some_asset.views

3 Responses to “Tracking Views in Rails”

  1. Rumble Says:

    Hi, I’ve been looking over this plugin recently as it looks like it could be the right fit for something I’m currently working on.

    One quick question, I see you can get the number of times an item has been viewed by doing @item.views, but is there a straightforward way of retrieving further information, for example getting the top 5 viewed items of particular viewable_type?

    I will download and have a play around to see if I can figure it out myself, but any heads up will be gratefully received.

  2. MichaelT Says:

    Brilliant!

    I am trialing this out on user profiles in my app. The user gets to see how popular thier profile is.

    Thanks.

  3. MichaelT Says:

    example: http://hunterartsnetwork.org/pages/profile/28

Leave a Reply