Rails + Google Analytics = easy goal tracking

October 27 Bullet_white By Andre Bullet_white Comments Comments

Google Analytics is an indispensable tool as you optimize the business side of your operation. If you haven't already set up goals in Analytics for viewing your pricing information, accessing the sign-up form, and signing up for an account -- go do it! It's vital information.

However, Google Analytics' goals have to be attached to a specific URL. What if there is no URL for an important goal? For example, the New Account goal for Scout is just the account/show page -- there's no specific URL to represent a newly created account.

flash[:analytics] to the rescue

For this situation, we found a nice clean solution with Rails' flash helper + a touch of Javascript.

Rails' flash helper is exactly the same one you use to display errors and notices. But you can pass anything in a flash. In our Accounts_controller#create action, we call:

flash[:analytics] = @account.free? ? "/goals/free" : "/goals/paid"

Then, in our layout, application.html.erb, within the same <script> tag in which we include Google Analytics:

<%if flash[:analytics]%>
  pageTracker._trackPageview("<%=flash[:analytics]%>");
<%end%>

It's as simple as that! We can register arbitrary goals in any action by setting flash[:analytics]. Within Google Analytics, just set the goals with the same names you've given the flash:

Key takeaways

  • Google Analytics is essential
  • you can register arbitrary URL's via Google Analytics' _trackPageview() call
  • Rails' flash helpers make it easy and clean to register analytics for any action in your app

Comments

comments powered by Disqus