2

I have a model which is an image gallery. I want to keep track of how many views the image gets. Currently I achieve this in the controller

 def show
    @article = Post.find(params[:id])
    @article.views += 1
    @article.save
 end

However, this only increments the views counter when accessing the full view (and this method also prevents me from caching the template). I also want to increment views when thumbnails are presented in a index collection view (because those are valid impressions as well), as well as searches, in other presentations of "likes", "favorites" etc.

In other words, any time the full image or thumb of the image is shown, I want to increment the views counter. Is there any pattern/paradigm for achieving this in rails?

Should I do this in javascript, such that after the page loads, I get a list of every post id on the page then ajaxly hit another controller which increments the views counter for all those posts?

Homan
  • 25,618
  • 22
  • 70
  • 107
  • 1
    Is there a reason why you can't use any of the several standard web server log analysis tools for this? Analog, AWStats, Perl in general, etc. are all fine. After all, everything you mention is already being recorded. – Eric Dec 26 '11 at 23:42
  • I'm hosting this rails application on heroku, I'm not sure that I can integrate with those tools. – Homan Dec 27 '11 at 00:19
  • You already have your solution in hand -- you just need to identify the places in the code where you "view" the article (including indexes), and then increment the counter. Handling this any other way (via a ajax javascript call) seems like it would only add complexity. – toddsundsted Dec 27 '11 at 00:42

1 Answers1

0

you can overwrite your routes. i did this once in a project:

/user_images/#{random}.jpg => i routed this to a controller, who tookes the image from the database, increment it and then serve it. this has also the effect, if someone crosslinks this image, you will count it.

BUT THERE IS A BIG BUT! it cost performance. i started this with an imagehoster, horribly! then i changed it. every hour i am passing the logfiles of my apache with an cronjob, and count the views. then i add it to the database. this fixed all my performance leaks.

Tim Kretschmer
  • 2,272
  • 1
  • 22
  • 35
  • I'm hosting my images from amazon s3, .... hm... I wonder if views can be downloaded from s3... – Homan Dec 27 '11 at 21:31