smkarber
smkarber

Reputation: 607

Rails: Track click on every link in Ruby on Rails application

The current requirement I have is to create a record in a Postgres DB whenever any object in the app is clicked. It is a large project with hundreds of links and pages. If a user clicks on an anchor, or a clickable div, or a button, I want to create a record in the DB.

The code for the call is as follows:

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

I am using it to track page transitions now, but how do I track clicking on a div or anchor with that function? Is it possible to do with JS in some capacity?

Upvotes: 2

Views: 1614

Answers (1)

fool-dev
fool-dev

Reputation: 7777

Look, you can use Ahoy analytics for Rails if you don't want to use this gem then you create this simply defining a method, at first I think your tracking table is app_events then your model is AppEvent then your models look like this relation

#=> user.rb
class User < ApplicationRecord

  .....
  has_many :app_events
  ....
end

#=> app_event.rb
class AppEvent < ApplicationRecord

  .....
  belongs_to :users
  ....
end

your 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

and your links look like this

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

Upvotes: 1

Related Questions