How to Add Google Analytics to a Rails Application

Coding Posted on Oct 06, 2023

Prerequisites:

  • A Rails application up and running.
  • A Google Analytics account. If you don't have one, sign up here.

Step-by-Step Guide:


1. Create a Google Analytics Property:
  • Log in to your Google Analytics account.
  • Click on "Admin" at the bottom left corner.
  • Under the "Property" column, click on "Create Property."
  • Fill in the details of your Rails application and click "Create."

2. Get Your Tracking Code:
  • Once the property is created, navigate to "Tracking Info" > "Tracking Code."
  • You'll see a block of JavaScript code under "Global Site Tag (gtag.js)." This is the tracking code you'll need.

3. Create a Partial for the Tracking Code:
  • In your Rails application, create a new file named `_analytics.html.erb` inside the `app/views/shared` directory (you might need to create the `shared` directory if it doesn't exist).
  • Paste the Google Analytics tracking code into this file.
  • Wrap the tracking code in a conditional to ensure it only runs in the production environment:

<% if Rails.env.production? %>
    <!-- Your Google Analytics tracking code here -->
<% end %>

4. Render the Partial in Your Main Layout:
  • Open `app/views/layouts/application.html.erb`.
  • Just before the closing `</head>` tag, render the analytics partial:

<%= render 'shared/analytics' %>


5. Verify the Integration:
  • Deploy your Rails application if it's not already live.
  • Visit your Rails application in a web browser.
  • Return to your Google Analytics dashboard and check the "Realtime" section. You should see at least one active user (which is you).

6. Dive Deeper into Google Analytics:
  • With Google Analytics now integrated, spend some time exploring the various reports and insights it offers. This data will provide a clearer picture of your audience's behavior, helping you make more informed decisions about your Rails application.

Conclusion:
Using a partial for integrating Google Analytics into your Rails application is a cleaner and more modular approach. It not only keeps your main layout file tidy but also allows for easier management of third-party scripts in the future. With this setup, you're well-equipped to leverage the insights from Google Analytics for your Rails application. Happy analyzing!

Leave a comment:

Comments (0)