Matthew Lindfield Seager

Matthew Lindfield Seager

Static Assets in Rails 7

Note for future me (written partially for myself, partially in answer to this SO question).

The home for static or public assets is the /public folder. In a default Rails 7 app you will find some error pages (e.g. /public/404.html) and icons (e.g. /public/favicon.ico) already in that folder. These are then served directly from the “raw” domain (at example.com/404.html and example.com/favicon.ico respectively). They are also accessible under example.com/public.

To reference these static images from ERB you need to make sure you tell Rails it’s an absolute path, not a relative one somewhere in the asset pipeline. This is done with a leading forward slash.

The following compares including a logo called logo.png when it’s stored in app/assets/images vs /public

<%= image_tag "logo.png" %>
<!-- becomes <img src="/assets/logo-1f04fdc3ec379029cee88d56e008774df299be776f88e7a9fe5.png"> or similar -->


<%= image_tag "/logo.png" %>
<!-- note the leading slash. This becomes <img src="/logo.png"> -->

<img src="/logo.png">
<!-- plain HTML if you don't want to use ERB tag -->

You can also use sub-directories; /public/images/logo.png would be available at /images/logo.png (or image_tag "/images/logo.png").

The second paragraph of chapter 2 of The Asset Pipeline Rails Guide contains more information. It mentions that this functionality depends on whether config.public_file_server.enabled is set.

In Rails 7 that config defults to ENV["RAILS_SERVE_STATIC_FILES"].present? in config/production.rb. If you’re using Heroku you can check this setting is present and enabled with heroku config:get RAILS_SERVE_STATIC_FILES.