如何在Rails中获取页面的数据/视图统计信息?

我想知道,如何在Rails中获得这些统计数据?

  1. / page / 1,/ page / 2这样的页面有多少独特的视图
  2. 他们来自哪个国家?

因为我想在这些页面下显示这些信息,我不想使用任何外部库,我希望我们可以有一些ruby gem可以做到这一点

谢谢

编辑1 – 我可以看到1-2个gem,如https://github.com/jkrall/analytical但仍然想要问SO社区

编辑2 – 我不认为上面的gem是我正在寻找它看起来它只是将第三方分析插入现有的应用程序

将Geocoder gem添加到Gemfile并bundle install

使用属性pageip_addresslocation创建一个Visit模型。

对于有问题的页面,在相关控制器中放置一个前置filter,或者如果要记录对每个页面的访问,请将它放在ApplicationController中:

 def record_visit Visit.create(page: request.fullpath, ip_address: request.ip, location: request.location.country_code) end 

Geocoder gem将location方法添加到请求对象,因此如果您需要的不仅仅是国家/地区代码,请阅读文档。

然后,您可以通过将以下内容插入控制器,再次在before_filter中显示特定页面上的视图数量,但这必须在上一个filter之后运行:

 def count_views @views = Visit.where(page: request.fullpath).count end 

由于您将大量运行此查询,因此您可能希望在创建访问模型时在页面属性上添加索引。

 add_index :visits, :page 

独特的视图很棘手,因为您当然可以拥有来自同一IP地址的多个访问者。 您可以将cookie设置为record_visit方法的一部分,然后如果cookie存在则不创建新的访问。

 def record_visit if cookies['app-name-visited'] return else cookies['app-name-visited'] = true Visit.create(page: request.fullpath, ip_address: request.ip, location: request.location.country_code) end end