Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Google Analytics custom events inside my rails controller?

What I want to do is use google analytic's custom event tracking from within my controllers, where the logic is done. I'm not quite sure how to put javascript code in my controller or if it is possible at all. How would I go about putting something like this inside my controller:

_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)

or

_gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);

thanks! And which one of these should I be using? EDIT:

Here's how I set it up based on the suggestion:

tracking code partial:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-ACCOUNT']);
  _gaq.push(['_setDomainName', 'sitename.com']);
  _gaq.push(['_trackPageview']);
  <%= render "layouts/ga_events" %>

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

_ga_events.html.erb (I added in the "value" parameter)

<% unless session[:events].nil? %>
  <% session[:events].each do |event|%>
     _gaq.push(['_trackEvent', '<%= event[:category]%>', '<%= event[:action]%>', '<%= event[:label]%>', '<%= event[:value]%>']);
  <% end %>
<% end %>

<% session[:events] = Array.new %>

application controller (added "value param)

  protected
    # GA event logger
    def log_event(category, action, label = nil, value = nil)
      session[:events] ||= Array.new
      session[:events] << {:category => category, :action => action, :label => label, :value => value}
    end

testing it in my Tasks controller:

def create
    @task = @user.tasks.build(params[:task])
    @task.author = current_user unless @user == current_user

    if @task.save
        log_event("Tasks", "Created", current_user.email, "123")
        redirect_back tasks_path, :notice => t('tasks.created')
    else
        redirect_back tasks_path, :alert => @task.errors.full_messages
    end
end

EDIT: here my GA output code, looks like everything is correct:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA_CODE']);
  _gaq.push(['_setDomainName', 'SUBDOMAIN']);
  _gaq.push(['_trackPageview']);
       _gaq.push(['_trackEvent', 'Priority', 'Created (day)', 'Label info', '']);



  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
like image 359
Matthew Berman Avatar asked Feb 14 '12 20:02

Matthew Berman


People also ask

How do I see events in Google Analytics using console?

To enable Analytics debug mode in your browser, install the Google Analytics Debugger Chrome extension. Once installed, enable the extension and refresh the page. From that point on, the extension will log events in your app in debug mode. You can view events logged in the DebugView in the Firebase console.

Where do you set up events in Google Analytics?

You can create and modify events in two ways: In code, using Google Tag Manager or APIs such as gtag. js or Firebase. In configuration, using Analytics Configure > Events options.


2 Answers

Jumping onto this suuuuper late, but here's a really quick option to the above. Just place this code in the controller that should trigger the custom event:

flash.now[:event] = "<script>_gaq.push(['_trackEvent', '#{category}', '#{action}'])</script>".html_safe

Much shorter than using sessions!

like image 94
user2371191 Avatar answered Oct 02 '22 14:10

user2371191


Here's how I do it, it's quite similar to how RoR implements flash. Essentially, on the server side you store up the events that you eventually want to push to GA via Javascript. When a page is eventually rendered, you render Javascript to push the events, and reset your store.

So...

# application_controller.rb
protected
def log_event(category, action, label)
    session[:events] ||= Array.new
    session[:events] << {:category => category, :action => action, :label => label}
end

.. call that method from your individual controller methods as many times as you please.

# application.html.erb
<head>
... other stuff...
<!-- Google Analytics -->
<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', '<%= CONFIG['ga_account_id'] %>']);
    _gaq.push(['_trackPageview']);
    <%= render "layouts/ga_events" %>
</script>

.. and the little partial referenced there is:

# _ga_events.html.erb
<% unless session[:events].nil? %>
  <% session[:events].each do |event|%>
     _gaq.push(['_trackEvent', '<%= event[:category]%>', '<%= event[:action]%>', '<%= event[:label]%>']);
  <% end %>
<% end %>

<% session[:events] = Array.new %>
like image 22
cailinanne Avatar answered Oct 02 '22 16:10

cailinanne