I'm trying to include Google Analytics in my Rails app but am having problems with Rails its asset pipeline.
I created a new file (app/assets/javascripts/google-analytics.js
) in which I included the Javascript code supplied by Google. To application.html.erb
I added the line: javascript_include_tag 'google-analytics' if Rails.env.production?
.
Unfortunately it doesn't work in production. After pushing to Heroku, the source code includes: <script src="/javascripts/google-analytics.js"></script>
. But it can't find the javascript file, i.e., if I click this link in the source code it produces the 404 error page. What am I doing wrong?
Update: It works if I add Rails.application.config.assets.precompile += ['google-analytics.js']
to production.rb
. It does now work if I add this line to assets.rb
instead of production.rb
. I would prefer to place it in assets.rb
to keep it uncluttered. Does anyone understand why it isn't working with assets.rb
?
Would it be a good alternative to directly include the JS file in the folder /public/assets/google-analytics.js
? Then I wouldn't need to include the file in /app/assets/javascripts/google-analytics.js
and I wouldn't need the precompile lines in production.rb
or assets.rb
?
Heroku log tail before update:
heroku[router]: at=info method=GET path="/assets/application-1d520c66bc88***583e462611.css" host=***.herokuapp.com request_id=*** fwd="***" dyno=web.1 connect=0ms service=2ms status=304 bytes=93
heroku[router]: at=info method=GET path="/assets/application-2b1c01f66fb87e***bd707657bc1acf7.js" host=***.herokuapp.com request_id=*** fwd="***" dyno=web.1 connect=1ms service=2ms status=304 bytes=93
heroku[router]: at=info method=GET path="/javascripts/google-analytics.js" host=***.herokuapp.com request_id=*** fwd="***" dyno=web.1 connect=1ms service=4ms status=404 bytes=1708
app[web.1]: Started GET "/javascripts/google-analytics.js" for *** at 2015-07-15 11:11:23 +0000
app[web.1]: ActionController::RoutingError (No route matches [GET] "/javascripts/google-analytics.js"):
app[web.1]: vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.3/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
etc.