I am trying to track each page of my Rails application, rendering this partial on the layout:
var analyticsId = '<%= Settings.env.app.analytics_id %>';
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<%= Settings.env.app.analytics_id %>', 'auto', 'trackEvent: true');
ga('send', 'pageview');
After adding the Google Analytics ID to the settings, I can see in my Google Analytics dashboard the visits to my users#sign_in
page but not the visits to my users#sign_up
page.
Inspecting both pages through the firebug console I see the spected result in the html code:
var analyticsId = 'UA-XXXXXXXX-X';
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g
m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto', 'trackEvent: true');
ga('send', 'pageview');
With 'UA-XXXXXXXX-X' = Settings.env.app.analytics_id which is defined in config/settings/app.yml under analytics_id.
We use devise to handle the signin/signup proccess and this is the part related to devise in the routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
confirmations: 'users/confirmations',
registrations: 'users/registrations'
}
ActiveAdmin.routes(self)
authenticated :user do
devise_scope :user do
root to: redirect("/home")
end
end
unauthenticated do
devise_scope :user do
root to: redirect("users/sign_in"), as: "unauthenticated_index"
get '/pages/:page', to: 'pages#show', as: "pages_show"
end
end
It seems that the problem was related to the fact that:
Rails 4.0 introduced a feature named Turbolinks to increase the perceived speed of a website.
Google Analytics doesn’t work for a Rails 4.0 or newer web applications. To be more precise, it won’t work for all pages. It can be made to work with a workaround to accommodate Turbolinks.
Making the long story short I have applied a workaround based on the answer in this post: Google analytics with rails 4