代码之家  ›  专栏  ›  技术社区  ›  smkarber

Rails:跟踪Ruby on Rails应用程序中的每个链接

  •  1
  • smkarber  · 技术社区  · 7 年前

    我目前的要求是,每当单击应用程序中的任何对象时,都要在Postgres DB中创建一条记录。这是一个有数百个链接和页面的大型项目。如果用户单击定位点、可单击的div或按钮,我想在DB中创建一条记录。

    呼叫代码如下:

    AppEvent.record_event(event_type: 'example', url: request.fullpath, user: current_user.name)
    

    我现在使用它来跟踪页面转换,但如何使用该功能跟踪对div或锚点的单击?有可能在某种程度上使用JS吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   fool-dev    7 年前

    听着,你可以用 Ahoy Rails分析如果您不想使用这个gem,那么您只需定义一个方法就可以创建这个gem,首先我认为您的跟踪表是 app_events 那么你的模型是 AppEvent 那么你的模型看起来像这样

    #=> user.rb
    class User < ApplicationRecord
    
      .....
      has_many :app_events
      ....
    end
    
    #=> app_event.rb
    class AppEvent < ApplicationRecord
    
      .....
      belongs_to :users
      ....
    end
    

    你的 application_controller.rb

    class ApplicationController < ActionController::Base
        protect_from_forgery with: :exception
        before_action :track_event, if: proc { user_signed_in? }
    
    
        def track_event
          current_user.app_events.create(event_type: params[:event_type], url: params[:url]) if  params[:event_type].present?
        end
    end
    

    您的链接如下所示

    root_path(event_type: 'home', url: request.fullpath)
    about_path(event_type: 'about', url: request.fullpath)
    news_path(event_type: 'news', url: request.fullpath)
    ...