Rails does not load assets located in public direc

2019-02-02 08:04发布

问题:

Hello i have assets in public directory (because of simplicity)

in layout i load

<link href="/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="/assets/css/jumbotron.css" rel="stylesheet">
<link href="/assets/css/application.css" rel="stylesheet">

and in Development it works well but in Production assets are not loaded.

My Development.rb

Web::Application.configure do
  config.cache_classes = false
  config.whiny_nils = true
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.raise_delivery_errors = false
  config.active_support.deprecation = :log
  config.action_dispatch.best_standards_support = :builtin
  config.active_record.mass_assignment_sanitizer = :strict
  config.active_record.auto_explain_threshold_in_seconds = 0.5
  config.assets.compress = false
  config.assets.debug = true
end

My Production.rb

Web::Application.configure do
  config.cache_classes = false
  config.consider_all_requests_local       = true # default false, zobrazuje errory
  config.action_controller.perform_caching = false # default true
  config.serve_static_assets = false
  config.assets.compress = true
  config.assets.compile = true # default false
  config.assets.digest = true
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
end

回答1:

This is because you have

  config.serve_static_assets = false

in your production.rb file.

From the Rails Configuration guide:

  • config.serve_static_assets configures Rails itself to serve static assets. 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.

And like that guide suggests, you really shouldn't rely on serving assets from public/ via your Rails app, it is better to let the web server (e.g. Apache or Nginx) handle serving assets for performance.



回答2:

Configuration changed for Rails 4 and 5.

For Rails 4:

config.serve_static_files = true

For Rails 5:

config.public_file_server.enabled = true