RoR:我如何计算特定链接的点击量

时间:2012-02-07 17:29:47

标签: ruby-on-rails counter

我是Ruby on Rails的新手

我想计算特定链接的点击次数,数据库中的存储计数,如果它只计算唯一链接,那就太棒了。

有宝石还是什么?

1 个答案:

答案 0 :(得分:2)

将此添加到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

确保您创建一个PageHit模型,其中包含网址字符串和计数整数。