Search code examples
ruby-on-rails-4asset-pipelineproduction-environmentruby-on-rails-4.1

Rails 4: run application in production mode after assets precompile gives assets not found issue


I am using rails 4.1.8

In production.rb file i have following:

  config.eager_load = false
  config.cache_classes = false
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = true
  config.serve_static_assets = true
  config.assets.js_compressor = :uglifier
  config.assets.compile = false
  config.assets.digest = false
  config.assets.debug = true

Now after running RAILS_ENV=production rake assets:precompile it precompiles all the assets and store them public/assets folder with file name application-ca4ad5e0582927b0a78c2b6feef3309b.js

after running application in production environment on my local, it throws error

ActionController::RoutingError (No route matches [GET] "/assets/application.js"):

I tried with changing values of config.serve_static_assets and others.. but still facing same issue.

The precompiled files are saved with digest values in their name, for ex: application-ca4ad5e0582927b0a78c2b6feef3309b.js but accessed as application.js, this is causing main issue.

Any suggestions here?? Thanks..


Solution

  • Refer this discussion here - Most of my assets suddenly return 404 after a push to heroku This is the exact issue we were facing.

    Adding 12 factor gem: github.com/heroku/rails_12factor fixes this issue. (This gem is now required if you're running Rails 4+ on Heroku). I tried adding gem 'rails_12factor' in the same repo you were working and this loads all assets just fine.

    Basically this rails_12factor gem is a combination of 2 gems viz. rails_serve_static_assets and rails_stdout_logging. Gem rails_serve_static_assets just sets this configuration to true. This is generally in your config/environments/production.rb

    config.serve_static_assets = true
    

    So in general, if we are developing a Rails4 app and we deploy on our own servers (say a dedicated server and not heroku) then setting this flag config.serve_static_assets to true is sufficient and we don't need to add rails_12 factor or any other gems. Here is the code of rails_serve_static_assets gem which is used by rails_12factor gem.

    module RailsServeStaticAssets
      class Railtie < Rails::Railtie
        config.before_initialize do
          if Rails.version >= "4.2.0"
            ::Rails.configuration.serve_static_files = true
          else
            ::Rails.configuration.serve_static_assets = true
          end
          ::Rails.configuration.action_dispatch.x_sendfile_header = nil
        end
      end
    end