Madhusudhan
Madhusudhan

Reputation: 8563

number of page views for a content

I am developing a website, where I need to track number of views for a particular content (lets say articles).

Its very similar to stackoverflow's views for a question.

I don't know how stackoverflow does it. Basically it should

  1. Increment the view when a user other than the article author visits the article. If he keeps hitting refresh button, it should not increment the view.
  2. Not increment the view if a visitor hits the refresh button continuously.But it should increment for the first visit.

I have a field in the database to hold number of views.

Anybody know how stackoverflow does it? Is there any plugin in rails which I can use? I guess I should use sessions and IP address to keep track... Should I make use of Logs? OR Google Analytics?

help...

Upvotes: 3

Views: 1673

Answers (2)

nfm
nfm

Reputation: 20667

Depending on how accurate you need it to be, you'll probably need to have a table containing records for which user has read which article. Their MAC address isn't sent with their HTTP request, and their IP(v4) address is probably not unique enough.

If you want to display the data (like stackoverflow does), you can't really use analytics.

It will be easier to add code to your controller methods to increment a database field than parsing logfiles and hooking into the database outside of Rails.

Pseudo-ish code (check API for syntax):

ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])
    # Create an ArticleReading (your join table) for this user unless one already exists
    current_user.article_readings.find_or_create_by_article_id(@article)
    # Count the number of users that have read this article
    @article_readings = ArticleReading.count(@article.id)
  end
end

You can use a plugin for this - I've used one before for marking things as 'read', which would probably be suitable (or at least adaptable). Have a read of this question, and hit up google.

Upvotes: 1

Nimesh Nikum
Nimesh Nikum

Reputation: 1839

I also don't know how stack overflow implemented it but I guess you can decide it by identifying mac address or current user id when updating views count. That means when first time user views a page, count will be updated and you can keep track of mac address. And again if same request comes up you should reject if it is from the system having same mac address.

Upvotes: 0

Related Questions