ankane / ahoy

Simple, powerful, first-party analytics for Rails
MIT License
4.23k stars 377 forks source link

[Idea] Tracking analytics per record/model #531

Closed vfonic closed 1 year ago

vfonic commented 1 year ago

Hi,

Before creating an issue, please check out the Contributing Guide:

https://github.com/ankane/ahoy/blob/master/CONTRIBUTING.md

Thanks!


Note: Just checked Contributing Guide. Perhaps this is better off on SO? Feel free to close the issue if so and I'll move the issue to SO.


I'm building a SaaS of sorts and I have many customers with their submitted various types of records in my database. I want to track every page view (Ahoy::Event) for every record#show, but I'd also like to be able to query only analytics related to a given record / customer. I've added this polymorphic association:

class Ahoy::Event < ApplicationRecord
  self.table_name = 'ahoy_events'

  include Ahoy::QueryMethods

  belongs_to :record, polymorphic: true
  belongs_to :visit
  belongs_to :user, optional: true
end

And in my record models I have this:

class Project < ApplicationRecord
  include Trackable
end

# frozen_string_literal: true

module Trackable
  extend ActiveSupport::Concern

  included do
    has_many :ahoy_events, as: :record, dependent: :destroy, class_name: 'Ahoy::Event'
  end
end

When trying to add record polymorphic association, I'm calling ahoy.track like this:

ahoy.track 'EventsList', record_id: record_id, record_type: record_type

I checked the source code and thought this would assign these attributes to ActiveRecord model attributes due to .column_names being called, but that's not the case. Anything else I could do?

I'm trying to avoid doing:

ahoy.track 'EventsList', record: record

...as I don't have those records loaded from the database, I only have record_ids and I know which record_type these record_ids belong to. Could this somehow be added as a code gem functionality? Are you open for accepting such PRs?

Thank you! 🙏

Again, feel free to close this if it's more SO type of question and I'll move it there.

vfonic commented 1 year ago

Nevermind, it's late and I've been writing bulls**t. 😅

I've just overwritten track_event in my config/initializers/ahoy.rb:

class Ahoy::Store < Ahoy::DatabaseStore
  # copied directly from Ahoy::DatabaseStore
  # ahoy gem 4.2.1
  def track_event(data)
    visit = visit_or_create(started_at: data[:time])
    if visit
      event = event_model.new(slice_data(event_model, data))
      event.visit = visit
      event.time = visit.started_at if event.time < visit.started_at
      # custom code
      event.record_id = event.properties.delete('record_id')
      event.record_type = event.properties.delete('record_type')
      # end custom code
      begin
        event.save!
      rescue StandardError => e
        raise e unless unique_exception?(e)
      end
    else
      Ahoy.log "Event excluded since visit not created: #{data[:visit_token]}"
    end
  end
end