哪种数据模型最适合用户视图的简单跟踪器?

时间:2011-09-14 01:35:36

标签: ruby-on-rails database ruby-on-rails-3 views tracking

这里有更多关于你们的学术问题。假设我想在rails应用程序的ruby中创建一个模型来跟踪简单的视图信息。我想记录user_id,查看页面的URI,并跟踪用户访问页面的次数。

模型A:执行此操作的一种方法是使用属性user_id和page(记录uri)创建模型视图,然后在每次用户打开页面时创建新条目。

模型B:第二种方法是向模型添加属性“page_views”,以跟踪用户访问该页面的次数。

优点和缺点:模型A会记录更多信息并导致比模型B更大的数据库。但是,模型B需要控制器搜索现有的用户页面组合,并向该条目添加视图,或者创建一个新的。这会导致数据库变小,但由于需要搜索现有条目,因此规模可能会更差。

所以我对你们的问题是:哪个更重要?我的想法错了吗?我在这里遗漏了一些东西(忽略了其他性能方面的考虑因素吗?)

1 个答案:

答案 0 :(得分:0)

用于跟踪用户活动的NoSQL方法:

model app/models/user.rb
class User < ActiveRecord::Base
  include UserModules::Tracker
  ...
end


mixin app/models/user_modules/tracker.rb
module UserModules
  module Tracker

    def get
      key = "user_" + self.id.to_s

      arr = Resque.redis.lrange(key, 0, -1)
      arr.map{|i| JSON.parse(i)}
    end


    def put(controller_name, action_name, details="")
      key     = "user_" + self.id.to_s
      created = Time.now.to_formatted_s(:db)}.to_json

      # silent exception handle, so you can do not run Redis localy
      begin
        Resque.redis.rpush key, {
          :controller_name => controller_name,
          :action_name     => action_name,
          :details         => details,
          :created_at      => created
      rescue
        nil
      end

    end

  end
end


controller app/controller/dashboard.rb
class Dashboard < ApplicationController
  after_filter :track, :only => :show

  # this action will be tracked
  def show
  end

  # this action will show tracking
  def logs_show
    render :json => current_user.get
  end

  ...

  private

  def track
    details = "any details...."
    current_user.put(controller_name, action_name, details)
  end
end

您需要安装Redis,我更喜欢使用Resque作为通过 Resque.redis 设置和初始化Redis的常用方法,因为它可以帮助您使用 resque-浏览跟踪网络

enter image description here

设置Redis的方法在我的gist