Ruby on Rails
Add OnyxMetric analytics to your Ruby on Rails app
Rails wraps pages in app/views/layouts/application.html.erb, so the tag goes in that layout's <head>. Feed the site ID through an environment variable and a config.x setting.
Copy your tracking snippet
In OnyxMetric, open your site's Site Settings and copy the tracking script. It looks like this:
<script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>YOUR_SITE_ID is the numeric ID of your site.
Add the snippet to Ruby on Rails
Configure the site ID
ONYXMETRIC_SITE_ID=YOUR_SITE_ID(Use .env with dotenv-rails, or set it in your host's environment settings.)
module MyApp
class Application < Rails::Application
config.x.onyxmetric.site_id = ENV["ONYXMETRIC_SITE_ID"]
end
endEdit the layout
Add the tag in <head> after the stylesheet and JavaScript tags:
<head>
<title><%= content_for(:title) || "MyApp" %></title>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
<% if Rails.configuration.x.onyxmetric.site_id.present? %>
<script src="https://app.onyxmetric.com/api/script.js?siteId=<%= Rails.configuration.x.onyxmetric.site_id %>" async></script>
<% end %>
</head>Wherever the variable is unset, the tag is skipped, so development and test are not tracked. With several layouts (for example admin.html.erb), repeat the tag or move it to a partial.
Turbo Drive swaps the body, merges the <head>, and pushes the new URL with history.pushState. The script watches pushState and replaceState, so Turbo visits are recorded as pageviews.
Check that it works
Load your live site and click through a few pages. Pageviews show up in the OnyxMetric dashboard within seconds.
If nothing arrives:
- View the page source and search for
script.js?siteId=to confirm the tag is present. - In the browser's Network tab, check that
script.jsreturns200and that requests go to/api/track. - Turn off ad blockers, or proxy the script through your own domain.
- Read script troubleshooting for other causes.
Troubleshooting
- Tag missing:
config/application.rbis read once at boot, so restart after changing the variable. CheckRails.configuration.x.onyxmetric.site_idinrails console. - Content Security Policy: if
config/initializers/content_security_policy.rbsets one, addhttps://app.onyxmetric.comtoscript_srcandconnect_src, or proxy the script.
Next steps
- Track custom events such as signups, purchases, and clicks.
- Identify users to tie sessions to accounts.
- Proxy the script through your own domain to get past ad blockers.
- Script attributes let you skip or mask URLs and tag events.