Ask A Question


You’re not receiving notifications from this thread.

How do I install Google tag manager in a rails 5 app?!

Muhammad asked in General
Hi guys, I'm having a hard time trying to know how to install GTM in my new rails app. I searched for some time but found nothing to guide me through it!

In your rails layout

Place the following code in the <head></head> tag:
<!-- Google Tag Manager -->
<% if Rails.env.production? %>
document.addEventListener('turbolinks:load', function(event) {
  var url =;  dataLayer.push({
    'virtualUrl': url
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
<% end %>
<!-- End Google Tag Manager -->

Place the following code in the start of the <body> tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src=""
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

PS.: Don’t forget to replace the “GTM-XXXXXXX” with your Google Tag Manager code.

Thanks a lot, Manuel!

If we want to test this in our localhost, do we have to change Rails.env.development?


Do we have a gem for that? except gtm_rails?

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,149+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.