Search code examples
ruby-on-railsasset-pipelineruby-on-rails-4.1

404 not found error for assets in rails 4 production enviroment


I am new to rails from java enviroment. I have few confusions in asset pipeline with rails 3 to 4.

Currently I am in rails 4.2.5 I created a sample app on my local environment. I created a new js from inside app/assets/javascripts and referencing it from the view , everything seems to working fine on my local environment.

After this I thought to test with production env how it works. Here are the steps I did.

  1. RAILS_ENV=production rake assets:clean assets:precompile [All the files created public/assets]
  2. Started the server in production mode rails server -e production
  3. Now when i browsed the page I am getting this error, "NetworkError: 404 Not Found - http://localhost:3000/assets/application-c5c431cb7c0a202f831a634922aaf1d536712002ae74334fb03ba4698b32b84c.js" in firebug.

When searched few threads , they suggest to add config.assets.compile = true. But I do not think so this is what the solution is, as it slows down the app.

Please help.


Solution

  • By default Rails4 will return a 404 if an asset is not handled via an external proxy such as Nginx. - https://github.com/heroku/rails_serve_static_assets

    I suggest you have a look at the rails_12factor gem, which includes the rails_serve_static_assets gem which will allow your Rails app to serve static assets (like your .js file).

    Edit:

    You may not need a gem for this (though I've not tried it):

    config.serve_static_files configures Rails itself to serve static files. Defaults to true, but in the production environment is turned off as the server software (e.g. NGINX or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won't be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app. - http://guides.rubyonrails.org/configuring.html

    In Rails 5, this config method has been renamed to config.public_file_server.enabled, the rails_serve_static_assets gem handles the correct naming depending on version.