Reputation:
I'm newbie in Ruby on Rails
I want to count hits to specific links, store count in database, and it will be great if it'll count only unique links.
Is there any gem or something?
Upvotes: 0
Views: 696
Reputation: 30404
Add this to your ApplicationController (app/controllers/application_controller.rb
):
before_filter :count_hits
def count_hits
# This tries to find a existing PageHit by the given url. If it does
# not find one, it creates one.
@hit = PageHit.find_or_create_by_url(request.url)
# Issues an UPDATE page_hits WHERE id = 123 SET count = count + 1
# on the underlying database layer. This atomically increments, so
# you do not run into race conditions.
PageHit.increment_counter(:count, @hit.id)
end
Make sure you create a PageHit
model, containing an url string and a count integer.
Upvotes: 2