Search code examples
javascriptruby-on-railsrubyherokuamazon-cloudfront

Rails 4 App - Heroku / Cloudfront - Assets not serving from origin properly


I have a rails 4 application in which we are using cloudfront as the CDN.

In the production.rb file, we have the following code:

config.action_controller.asset_host = "example3579.cloudfront.net"

We have done some pretty thorough asset separation. This may not be advisable from an asset pipeline standpoint, but it should make debugging this issue pretty easy.

The particular page I'm working on is the users#edit view, but the problem is universal.

The users#edit action uses it's own layout: views/layouts/user_edit.html.erb

The views/layouts/user_edit.html.erb file calls this javascript.

<%= javascript_include_tag 'user_edit'%>

assets/javascripts/user_edit.js

//= require jquery
//= require jquery_ujs
//= require jquery.validate.min
//= require ./webarch/form_validations

On the localhost, this works. I can access the js in the browser like this:

http://localhost:3000/assets/user_edit.js

But on production with heroku, the site looks for this file:

<script src="http://example3579.cloudfront.net/javascripts/user_edit.js"></script>

The file doesn't work. I can't access in the browser and the javascript does not render on the page. I have precompiled the assets.


Solution

  • Add gem 'rails_12factor', group: :production # Helpful for rails 4 assets on heroku

    And in /config/environments/production.rb

    config.assets.compile = true
    

    This should work