Back to Blog

Get in Touch

Tracking Views in Rails

By Dave Naffis June 4, 2007 in

Missing

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.

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
Medium

Dave Naffis

David is an entrepreneur and software developer with demonstrated experience in software services, product development, strategy, and operations. He is a co-founder of Intridea, an Inc 500 winning software development firm where he oversaw several successful product spinouts. Before starting Intridea, Dave ran his own Ruby on Rails consultancy and worked as a software engineer and architect at companies including AOL, Cisco, and McKinsey. He holds a masters in Systems Engineering from The University of Virginia, has contributed to a number of open-source projects, and has spoken at numerous regional and national conferences.

More from our blog

Welcome to Intridea

Read Now →
X

More posts by Dave Naffis

Dave Naffis

Four years ago, what started as a team of three people with a conviction t...

Dave Naffis

In this new blog series, Why Your Company Needs a Rails Development S...

Dave Naffis